CLAS201, 2017-05-01

LAND AND SEA

I. EXTENT

Greeks did not call themselves “Greeks.” They called themselves “Hellenes.” Their country was called “Hellas,” not Greece.

  • In terms of topography, Greece was wherever Hellenes lived.
A) Greece Proper:
  • Peloponnesus
    • Archaea, Arcadia, Messenia, Laconia
    • The area in southern Greece, south of Corinth. Notably, Sparta and Olympia can be found here
    • Messenia was conquered by Sparta, which enslaved the region
  • Attica, Boeotia, Thessaly, Aetolia, Epirus, Macedonia
    • These were regions of Greece
B) Ionia, and the Aegean Islands
  • Miletus, Ephesus, Halicarnassus (all cities)
  • Samos, Naxos, Paros, Lesbos (cities Mytiline & Methymna), Delos (all islands)
C) Crete: Cnossus
D) Black Sea
  • Sinope, Trapezus
E) Magna Craecia
  • Taras (Tarentum), Neapolis, Syracuse
    • Syracuse was maybe the largest city state. It was compared to Athens in terms of size, miltary power, and cultural accomplishments
F) Around the Mediterranean
  • Cyrene, Massilia, Emporion, Naucratis
    • Naucratis was a fully Greek city in the middle of Ancient Egypt. It was a trading city.

II. LAND

A) Topography was rugged. 75% of modern Greece is mountainous.
  • Implications
    • poverty: Greeks tended to be economically poor since ancient economies were based mainly on agriculture
    • Polis Culture: Greek states were small and independent (at least, ideally) perhaps because the regions were divided into small geographical units (like islands).
    • Communication by land was difficult, so they turned to the Sea.
B) Agriculture and Livestock
  • Mediterranean triad: grain (wheat, barley, oats), olives (esp. for oil), and wine
    • also ate meat (cattle, sheep, goats), fish, legumes, and nuts. New findings suggest Greeks ate more meat than first thought.
  • Used horses for war and travel, and oxen for power

III. THE SEA

It’s worth noting that the Greeks were one of the few powers to never really have an empire, with the exception of one maritime empire.

They liked the sea… a lot. If some Greeks were lost, but they found the sea, they’d be happy.

HISTORICAL BACKGROUND

I. BRONZE AGE: 2000-1200 BC

Minoans were quite advanced and developed a Greek-speaking civilization of their own: the Mycenaeans Mycenaeans started to build rich tombs and monuments around 1600 BC

  • discovery dated to 1600 BC indicated a wealthy enough society to build these rich tombs.
  • this also indicated some level of political cohesion, where the gov’t would be able to collect people’s wealth to fill these tombs

Mycenaeans main city was Mycenae, made of a bunch of city states with a well-fortified citadel in the centre.

ca. 1600 BC Mycenaean collapse

  • controversial: tied with the fall of Atlantis (fictional?)

Note: Minoans spoke Greek, but were not Greek… They were highly influential on the Mycenaeans

II. Dark Age (1100-750BC)

Eventually, the people stopped writing and became illiterate. It took around a century for the Mycenaeans to collapse (1200-1100BC)

The economic, demographic, and cultural recovery began. It was heavily influenced by the East, which led to a different Greek civilization afterward.

Agriculture was more effective, and the Greeks began building large monuments again.

Iron Age: 1050BC

  • Iron technologies came from Cyprus (likely)
  • people did use iron beforehand, but mostly just for trinkets. This age came with metallurgy, where the Greeks learned to melt down the iron, carbonate it, etc…
  • slightly contradictory, because this important technological advancement occurred during the (supposed) Dark Age

Ionian Migration: 1050-950BC

  • During the Dark Age, there was lots of movement. After the Trojan War, peace eventually returned, and mainland Greeks migrated to the Aegean islands and the central coastal area of Asia Minor
    • This was somewhat documented by Thucydides
  • Need more info…

III. Archaic Period 750-480BC)

Note, 750BC is not exact. By 750, the Greeks had already been thriving (much more than it did during the Dark Age, at least)

Civilization began to read and write again. Also began to build monuments and advanced cities again.

Around this time, the Greeks staved off Xerxes’ Persian Invasion. This also marked a renaissance for the previously struggling civilization.

A) City-states arise (750-700BC)
B) Colonization
C) Age of Tyrants
  • elite families are constantly competing for standing. At some point, they figured that if they can get the peoples’ support, they can gain significant influence. From here, they came to power with the peoples’ support.
  • eventually, however, the people stopped supporting the tyrants, and democracy began. In some cases, aristocracies began.
  • Ancient Greeks were (probably) much more democratic than we are right now.

CLAS201, 2017-05-03

HISTORICAL BACKGROUND, cont’d

IV. CLASSICAL GREECE: 480-323 BC

The beginning of this era was marked by the accomplishment of staving off Xerxes’ Persian invasion.

  • Greeks were committed to freedom, so this was a big thing for them
A) Greek victories over the Persians
  • against Darius I: Battle of Marathon (490 BC)
    • Darius sent an expedition to punish Athens
    • Greeks smashed the Persian invasion with a relatively small force
      • Spartans were the dominant power in Greece at the time, and agreed to help but only after the end of their on-going religious ceremony
        • they were too late, but the Greeks showed them to Persian bodies
  • Xerxes (successor of Darius I): Salami/Plataea (480/479 BC)
    • the Battle of Thermopylae (movie 300), where the Spartans held the Persians at The Hot Gates
    • The Persians had a large naval army, but it was felled by a tempest.
    • This was the second Persian invasion against Greece; a response to the failure of the first invasion
  • Indicative of freedom.
B) Delian League/Athenian Empire: (477-404 BC)
  • After the two successful defenses against the Persians, the Athenians felt confident in their own power, and strove to defeat the Persians completely. The formed an alliance: the Delian League
    • This became over-confidence, and the Athenian Empire became possessive.
      • As people became aware that the Persians weren’t much a threat anymore, they figured it was time to leave the Delian League/Athenians and cease large payments to the Empire. The Athenians would not allow anyone to withdraw the League.
      • The Athenians oppressed other Greeks
    • Note: Athenians were the most powerful on the sea.
C) Peloponnesian War (431-404 BC)
  • The Peloponnesian League was dominated by Sparta.
  • Sparta and its allies became worrisome of the oppression of other Greeks by the Athenian Empire
    • So, they went to war against the Athenians.
    • Note: Thucydides’ wrote of this war with brilliance, and thus popularized it. He was an Athenia historian and general.
      • Thucydides analyzed the war and what caused it. Sparta and Athens were indirectly involved in a previous war, which caused a bit of political difference.
      • The real cause, as stated by Thucydides, “Sparta was afraid of growing Athenian power.”
  • In short, Sparta and the Athenians were happy with each other around the Persian invasions. However, tensions grew as the Athenians grew in power
  • The Spartans won and conquered the Athenians
    • Sparta was considered the most powerful state even when the Athenians reached the peak of their powers.
    • During the second year of the war, Athens suffered from a plague that killed a quarter of their population
      • they “won” the war for the first 10 or so years, despite the devastating plague.
    • The Athenians lost, eventually, when they decided to try and conquer Sicily (which was as powerful and rich as any other city in Greece).
      • This cost the Athenians two of their forces, but they stil hung on.
  • The Athenians lost in 404 BC

It’s relatively easy to follow the 500-400 BC century. It’s solidly divided into three sections/events. In the time period of 404 BC and 323 BC, there were many powerful states

The shifting hegemonies:

  1. By 395 BC, Sparta was fighting for its life. Beforehand, they were dominant, but the Greeks grew restless of their “rule.”
  2. By 377 BC, the Athens re-established their maritime empire. They promised to be nicer than their previous effort. The Greeks believed them

    • Between 377 and 371 BC, they were considered the dominant power in Greece
    • Eventually, by the mid 350s BC, the Athenians lost their renewed empire
  3. 371-362 BC, Thebes was the dominant power

    • They were considered very innovative and creative leaders
    • Pelopidas and Epaminondas were the main leaders of Thebes, which was (more or less) a democratic state.
    • These two came up with new ways to fight wars, and were aggressive
    • Pelopidas invaded the north
    • Epaminondas invaded Sparta itself.
    • Note that Sparta had no walls. Sparta figured that they were so dominant and powerful, they invaded others—not the other way around.
      • He was unsuccessful, and the Thebans withdrawed.
  4. With all the in-fighting in Greece, a semi-state known as Macedon grew.
    • Herotudus, who wrote in the 440s BC, was fine with considering Macedons as Greeks.
      • Other historians, like Demosthenes, didn’t. Note: Demosthenes was a powerful speaker, using his oratus against the Macedons, whom he called barbarians.
    • Regardless, Macedons became more and more Greek as time went by. In the early decades of 300 BC, they were in bad shape. By 360 BC (after a bunch of wars within Greece), Philip II of Macedon ascended as a briliant diplomat and military innovator.
      • He brought the Macedons up, and expanded.
  5. Battle of Chaeronea (338 BC)
    • Philip II of Macedon fought against Thebes (and Athens), and smashed their armies. They pratically dominated all
      • Sparta, did not go to Chaeronea to fight. When Philip II didn’t want to go through the trouble of conquering Sparta. After this, Sparta didn’t do much.
    • After this battle, Philip II controlled the Greeks. He called for a conference and formed an alliance against the Persians.
      • He managed to get the Greeks (who were initially against him) to unite with him based on their collective hatred against the Persians.
    • Philip II had a son: Alexander the Great, who lead the Greeks against the Persian Empire.

Alexander the Great was extremely aggressive and fucked everything up.

  • In a few years, Alexander conquered all of Persia. By 323 BC, he was the King of all of that shit.
    • This empire spanned from Macedonia down to Libya all the way to India
  • He died in 323 BC (rumours of poisoning).

V. HELLENISTIC ERA (323-313 BC)

After Alexander’s death, his generals took over reign, as he had no apparent heir to the throne. He had a brother and an unborn son who were both unavailable. A few different powers arose, until the Romans came and shit on everyone.

  • Macedonia continued to reign
  • Seleucid Empire
  • Ptolmaic Empire
  • Pergamum

MINOAN CIVILIZATION

The Minoans were not Greek, but highly influence the first Greek civilization (the Mycenaeans)

  • The Minoans had an impact on the collective memories of the Greeks

I. MINOANS IN GREEK MEMORY

A) Mythology: Zeus and Europa, Minos and the Minotaur, etc
  • Zeus had a lust for Europa, and came down to her as a beautiful white bull with rosy breath. Europa climbed on his back and Zeus took her, across the sea, to Crete, and “had his way with her.”
    • Europa conceived a child named Minos, the King of Crete
    • One incident: Minos was to sacrifice a bull (given by Poseidon) to the Gods. He saw the bull was very elegant, and elected not to.
      • Poseidon was pissed off, and some shit happens, and someone gave birth to the Minotaur.
  • As expected, the Minoan civilization was named after Minos.
B) “History”
  • Both Herodotus and Thucydides identifies Minos as the first thalassocrat. Thalasso referred to the sea.
  • Crete has many major population centres.

II. TIMELINE

  1. 3000-2000 BC: Peasant Culture
    • no elites who can marshall the resources of the community (to build big buildings)
  2. 2000-1700 BC: First Palace
    • the Minoans garnered enough wealth to build sophisticated buildings
  3. 1700-1400 BC: Second Palace
    • 1700 BC marked the destruction of the first palaces.
      • thought to be earthquake-related
  4. 1450 BC: Mycenaean Takeover
    • The Minoans existed on Island Crete. The Mycanaeans were on land in Greece. The Minoans influenced the Mycanaens, who then invaded sometime around 1450 BC. Still, they perserved the main palace of the Minoans at Cinossus
  5. 1400-1200? BC: Post-palatial period

III. NATURE OF MINOAN SOCIETY

A) Matriarchal?
  • Minoan art heavily featured women.

    “The promience of females in Neopalatial art, important mortal women and goddesses, makes it possible to imagine that women dominated Neopalatial society, perhaps even politics. All human societies, however, ancient and modern, have been patriarchies with men in positions of authority; no matriarchy has ever been documented. But Neopalatial Crete offers the best candidate for a matriarchy so far.”

B) Art
  1. Frescoes: showed lively, natural, and non-propagandist content
    • people fishing, dolphins, dancing, etc
  2. Seals: intricately carved miniatures
  3. Use: not for political/religious propaganda as in Egypt and Mesopotamia
C) Architecture
  1. Palaces: “agglutinative” style with large open courtyard surrounded by many, multi-purpose rooms (residential, ceremonial, storage, manufacturing)
  2. Villas: similar in decoration and structure except for the lack of a central courtyard
D) Economy
  1. Domestic: highly centralized “command” economy
    • The commanders would collectively figure out what the civilization needed.
    • The Central Palace declared what each region needed to produce
    • Though there’s recent evidence for entrepreneurship on the peripheries. Still, the economy was highly centralized
    • Linear A
      • A script that the Minoans used to record things coming in and out of the palace. These were economic records
  2. International trade: agricultural products (olive oil, textiles) for luxury goods (gemstones, ivory, amber) and metals (gold, silver, copper, tin)
    • Copper and tin were popular due to their usages in making bronze
    • Note: There are suggestions that trade was largely cermonial-based. Personal relationships between rulers invited trades as dowries.
      • Guest-friendship was very prevalent back then. Guests, strangers or not, were considered friends, and this guest-friendship could last for generations. As a result, rulers and kings would give goods to other states as dowries and gifts.
E) Politics
  1. Monarchy?
  2. One central authority (Cnossus) or multiple?
    • Cnossus would, potentially, have one central seat (a throne, per se)
    • If there were multiple authorities, then different states (of different rule) should have different imageries and cultural significances. For example, different nations have flags. However, in Greek society, all the states used a double-axe as their popular symbol, suggesting they all fell under one rule/authority/culture.
  3. Wider Aegean (Cyclades, mainland esp. Athens)
    • There are many Minoan sites with similar architecture/art located in this region
    • Certain Greek myths suggest that some mainland states were controlled by the Minoans.
    • Side note: 1628 BC: Large volcanic eruption (the “Greek Pompei”)
F) Religion
  1. Mother-Goddess?
    • Priesthood was largely female, consisting of mostly priestesses
    • It’s also likely that were were multiple gods being worshipped
  2. Natural sanctuaries
    • No monumental temples
    • Minoans used caves (to worship chthonic and/or fertility deities?), hilltops (for Olympian deities), trees
      • this is in contrast to the Greeks of later times, who built temples for so many of their Gods and Goddesses
      • this is also in contrast to other nations like Egypt, who built massive free-standing temples for their religion
    • In caves, body parts were found, suggesting this was a place for healing
      • A Chthonic deity is associated with the ground (and what’s under it)
    • Note: it does seem like they had some shrines within their palaces
  3. Summoning rituals
    • Instead of the divine presence of a cult statue (?)

CLAS201, 2017-05-08

MYCENAEAN CIVILIZATION

Introduction

Minoan-influenced Greek kingdoms, but largely discontinuous with classical Greek culture

Timeline

  1. ca. 2000 BC: “Greeks” enter Greece
  2. 2000-1600 BC: Pre-Mycenaean
    • no monumental architecture, etc.
  3. 1600-1400 BC: Early Mycenaean
    • some monuments were built, and rich tombs were amassed
  4. 1400-1200 BC: Palace Period
    • Some felt that Mycenaeans just didn’t build palaces. There are tombs (not very spectacular, though) but no palaces.
      • Either Mycenaeans just didn’t build palaces, or just that nothing survived.
      • Architecture that had survived could have been built over by future civilizations, but there’s little evidence for that as well.
      • Still, lots of art and treasures have survived
  5. 1200*- Major upheaval
    • Lots of controversy over what exactly happened.
    • Much of the Mycenaean strucutres were destroyed. After this, the Mycenaean culture began to subside.
  6. 1200-1050 BC: Sub-Myceaean
    • Lots of Mycenaean-style pottery survived, but it appears that the quality of these potteries deterioted over time. Art quality went down as well. Based on this, it’s clear that there was a slow but noticeable decline after the Major Upheaval.

Note that 1700-1450 BC was considered the Neopalatial period of Minoan Civilization.

A) Classes

There’s no doubt that the Minoans had classes in their social structure. However, there’s just no physical evidence leftover from their times to declare it for certain.

  1. Kings and Elite
    • Wanax
      • means King based on how he’s mentioned in the Linear B tablets
      • Later Greeks have a word “anax” that stood for “High King”
      • Agamemnon was the high king, called “Wanax” or “Anax”
    • Lawagetas
      • A high-ranked military leader (or just a general status)
    • Basileus
      • A regular King, of later Greek times
      • Kings under Agamemnon were called “Basileus”
      • A person who is set over local areas within the Mycenaean kingdom. A mayor of the town or village
        • When Mycenaean civilization went down the tubes, it’s very likely (and there’s some evidence) that some of these smaller towns survived, and had their Basileus rule over them
  2. Officials (the literate and others(?))
    • Bureacracy required some literate groups of people to command the masses
    • Low number of Officials. There appears to have been as few as 10 officials who wrote legislation
  3. Artisans and “Free” Farmers
    • There were lots of craftsmen who made things in palaces. E.g. those who built chariot wheels and extracted olive oil
      • There were things being built outside as well, in towns and villages, but most of the construction work happened in palaces
    • “Free” Farmers weren’t slaves. They weren’t wealthy or well-off, but they were free.
  4. Slaves
    • Some scholars suggest that Minoans didn’t have slaves. They had a much more positive culture over other nations
      • Opinions have swayed, and it seems that an advanced civilization like the Minoans must have had (cheap) slaves to get all their work down
    • In the ancient world, virtually every advanced civilization had slaves as an integral part of their society. That’s how shit got done
B) Architecture

Minoans didn’t have fortifications. Their palaces weren’t surrounded by walls. This suggested that they owned the sea (they were an island civilization, after all). If they owned the sea, they’d naturally not expect any invasions on land.

The Mycenaeans were big on walls and defense.

  1. Fortifications
    • Cyclopean walls
      • The Cyclopes were giants among the ancient Greeks. Later Greeks thought these huge blocks of stone were moved by the Cyclopes, hence the name
  2. Palaces
    • Megaron design with Minoan decoration
    • Mycenaean palaces were different in structure and outline from the Minoans’
      • However, the artistic decoration was adopted from the Minoans
      • The Megaron is the main room in the palace. It contains a large, ceremonial harp in the center with 4 pillars surrounding it. One side of the room would have a single chair (the King’s throne).
        • Not found in Minoan palaces
    • Influenced by/based on Greek houses. The basic outline of the palace was based on what the Mycenaeans understood as a house. The palae was the King’s house.
  3. Graves: especially tholoi
C) Art
  1. Frescoes depicting not just typical Minoan themes but violent scenes as well (hunting, war, etc)
  2. Art in miniature
    • figurines, seals, inlaid daggers of silver and gold designs
D) Economy
  1. Highly centralized: note Linear B tablets
  2. Raid and Trade

    For in early times the Hellenes and the barbarians of the coast… were tempted to turn pirates… They would fall upon a town unprotected by walls, and consisting of a mere collection of villages and would plunder it; indeed, this came to be the main source of their livelihood, no disgrace being yet attached to such an achievement, but even some glory

    Thuc. 1.5.1

E) Religion
  1. In art: Mycenaeans seem to have adopted ritual and symbols from the Minoans
  2. Places of worship
    • Little evidence of natural places (caves, mountaintops, trees) like Minoans, but there are free standing shrines and cult statues
    • Mycenaeans liked coiled-snake statues (of clay, presumably) a lot. The symbolism of the snake is prominent in later Greek civilization
      • represented: healing and powers of the earth
  3. Gods
    • As many male as female in Linear B tablets
      • It’s very unlikely the Mycenaeans had a single mother goddess -
    • many names of the gods correspond to later Greek gods’ names
F) Militarism
  • artistic techniques and themes based closely on Minoans but with military themes
    • hunts, wars (against barbarians)
  • walls and weapons were prominents

CLAS201, 2017-05-10

Suggestions as to why the Mycenaeans fell

  • Earthquakes that caused massive destruction?
  • Trade routes collapsed?
  • Common people had enough of their rulers, and rebelled?
  • Environmental issues, like droughts?
    • Tree-ring growth and ice-core samples suggest that there was a drought. This put stress on the kingdoms in a dominoe-effect manner
  • Combination of things

It is obvious that man is by nature a political animal

Aristotle, Politics 1253a

Greek Polis

I. DEFINITION

A geographical area comprising a city and its adjacent territory, which together make up a single, self-governing political unit

Ancient Greence, p. 104

II. FORMATION

A) Reasons for synoecism (late Dark Age)
  1. Growth in population and economic sophistication
    • When the Mycenaeans collapsed, population took a hit. Eventually though, it improved. By 750 BC, it was a lot better
    • Growing sophistication in metalwork
      • Greeks were no longer in the bronze age. They used iron for most of their tasks. Iron required more expertise to use, hotter furnaces to smelt, etc
      • The complexity created a need for a larger number of craftsmen
      • The complexity introduced in trade also advance the civilization. To import iron, you needed other civilizations with the necessary infrastructure and wealth.
  2. Protection, since early urban centres were fortified
  3. Religion with urban festivals drawing surrounding populations
  4. Compulsion?
    • Religious centres were in urban areas, and large festivals/parties drew in lots of people
    • This made people feel “together”, due to these regional religious centres. Even though they were from different city states, they were united in religion
      • if each city state were separate and fiercely independent, why did they feel Greek at all?
      • The festival of Olympia (Panhellenic) brought Greeks from all different city states
    • Eleusis was a town within the Athenian state. Stories say Eleusis attacked Athens, not the other way around.

III. DIVERSITY (over 1000 named in sources)

A) Typical polis

Sicyon, 360 sq. km., less than 1000 citizens in population of 3000+

B) Untypical poleis
  1. Athens: 26000 sq. km.
    • 25,000-30,000 citizens in total population of 275,000
      • during the time of the Athenian democracy in the Classical Era
      • How come only 10% of the population are Greek citizens?
        • Athens was a major political centre. Lots of slaves and metics (for trade, etc)
    • Synoecism by wide granting of citizenship
      • How did Athens become so large with such a high population?
        • They just went around and told people to join them in return for making them full citizens
      • Thucydides

        King Theseus went around and shut down town halls and told the town they were going to be Athenian citizens

    • Not terribly large, but much larger than Sicyon
    • The Athenian Empire spanned from Athens to Marathon
      • Also had a border fort at Phyle
  2. Sparta: amalgam of 4 villages, plus Amyclae later
    • Controlled a larger area than Athens did.
    • Some sources stated that Amyclae was forced to join
      • It was relatively far away, while the 4 villages were close
    • no common religious centre (Athena v. Apollo) and no wall.
      • Sparta reflected its amalgamation. The Amyclae didn’t recognize themselves as Spartans even a century after the amalgamation—and nor did the Spartan state. During a festival to Apollo, the Amyclaens would return to their region.
    • Incorporated wider areas through conquest
      • Very different from Athens
        • Indicative of the contrast between Sparta and Athens, while both are quintessentially Greek. They often differ, but were both Greeks.
      • Sparta was known to be laconic. Defeated people while saying little.
    • At its peak, Sparta probably had 5,000 full citizens (at the beginning of the Classical Era).
      • 2,000 by the Hellenistic Era
      • While the area was easily twice the size of Athens, they only had a small fraction of the population
    • Conquered Messenia, along with its own Laconia territory

IV. UNIQUE CHARACTER: CITIZENSHIP

A) Polis is defined as its citizens

Not its geographical extent or its ruler/bureaucratic structure

A polis is not where there are stones or wood, or the craft of builders; a polis and its walls are found wherever there are men able to defend themselves

Alcaeus, fr. 426; trans. M. A. Sears

Background:

  • The Athenians got too excited during the Peloponnesian war. They decided to conquer Sicily, and so sent two armadas to the maritime state. The Athenians got slapped.
    • Lost both fleets and thousands of soldiers.
  • Nicias tried to convince the Athenians to not attack Syracuse.
    • Unfortunately(?) he was outwitted (or just generally not paid attention to).
    • He tried to argue against the attack, but was made commander of the attack anyways
  • The Thucydides story is, apparently, epic.

And then look at yourselves, mark the numbers and efficiency of the hoplites marching in your ranks, and do not give way too much to despondency, but reflect that you are yourselves at once a city wherever you sit down…The one thought of each man being that the spot on which he may be forced to fight must be conquered and held as his country and stronghold … Men make the city and not walls or ships without men in them.

General Nicias, Thuc. 7.77

  • While marching home from the slapping at Sicily, Nicias told his soldiers that they are not lost, or in despair. They are a city, themselves, simply because they are citizens.
    • “Men make the city and not the walls or ships …”
B) Principle of citizenship: equality
  1. At Athens, all citizens rule and are ruled in turn
  2. In Sparta, all citizens (homoioi) live together with the same lifestyle
  3. Caveat, equality may have arisen from the idea of the value of each citizen
    • kaloi kagathoi v. kakoi
      • When Greek city states first arose, they were virtually all aristocracies. Some were considered elite. Others, commoners.
        • The kaloi kagathoi referred to the elite
        • The latter referred to, literally, the “enemy.”
      • Through a series of circumstances, those who had a modest value (like commoners), came to be worth the same as the elites. This wasn’t how it originally was.
      • Athens became a full radical democracy when it depended on its navy for military power.
        • The navy was powered by the commmoners. Thus, the exact time Athens became a democracy corresponded to the commoners starting to power their navy.
      • In short, equality was developed. It didn’t originate from the beginning.
    • Early poleis were aristocracies with distinct elite class
    • Suppose a citizen won a lottery of some sort. The person became a magistrate
      • The idea is that every citizen is competent (enough) to rule
    • Leaders should be sophisticated thinkers—although everyone strove to be such.

V. WHY NOT KINGS? (Sears, p. 61)

Having kings or a monarchy seems like the logical approach for a civilization at time. Why didn’t the Greeks have kings?

A) Wealth
  • Elite were not able to monopolize limited wealth entirely
    • wanakes v. basileis
    • So, the elites were unable to have a dominant power/family
B) Religion
  • Rulers did not monopolize access to the gods, as opposed to other civilizations
C) Military
  • In the Greek hoplite phalanx, all soldiers stood together (somewhat out of necessity).
    • The traditional single-arm shield has a handle in the middle. The Greeks decided to develop a large round shield with two straps
      • One in the middle, one on the side. The center strap was held by the forearm, but the hand grasped the handle on the end. This makes it easier to maneuver with the shield.
      • This left the off-hand somewhat exposed. This was covered by the next unit in the phalanx.
    • This made people feel equal in the military

CLAS201, 2017-05-15

Athenian Democracy

I. CHARACTERISTICS

A) Direct (not Reprsentative)
  1. Assembly
    • Discussed and decided all legislation
      • Was supreme: had a lot of power and freedom to do whatever they wanted
      • Contrast with Sparta’s Apella and Roman assemblies
    • At the end of the discussion, all the citizens voted, directly, for the decision they were going to make
      • Not too many citizens actually spoke, but they could.
    • Today, we don’t have direct democracy
  2. Courts
    • Very large juries (as high as 1501) chosen by sortition suggested the whole demos & prevented bribery
      • Required a majority vote
    • Major trials (like treason) were held in Assembly itself
  3. Magistrates
    • Chosen by sortition (lottery) to rule and be ruled in turn

II. DEVELOPMENT

A) Solon (594 BC), a mediator
  1. Eliminated Debt Slavery and redistributed land
    • Farmers, for example, need to borrow resources when their crops weren’t growing just so they could feed themselves.
      • This debt led to many citizen families being sold into slavery
      • Solon eliminated this
    • The elite were dominating the land that was available
      • There was a class of people who had to give a portion of their produce/land to the elite. Solon also eliminated this.
        • Origins of this were unknown
    • Still, the common citizens wanted Solon to redistribute all the land, which he couldn’t do.
      • Also, this reduced the income of some elites, so they weren’t happy as well.
  2. Set up property classes (though only top two could stand for major magistracies)
    • Solon was a mediator, not a democrat. As such, he didn’t really have any regard for the status of commoners and elites.
  3. Established Boule (cf. Areopagus) to organize business of the Assembly
    • Boule just means “council”
      • Solon regulated/set the powers of the council/assembly.
        • He declared what they could or could not do.
      • WHen the assembly decided on something, the Boule ensured it would be followed through.
    • Areopagus meant the council that met on the hill of Ares (the traditional council)
    • Issues: the people didn’t want the council to make all the decisions. Solon argued that juries of common people needed to make decision as well
      • If a common person was dragged to court in front of the Areopagus, and is declared guilty, he could appeal with the jury
        • Some scholars think that’s all the jury was (an appeal court)
        • Others believe the juries actually tried their own legal cases
  4. Set up jury courts (appellate) open to all citizens
  5. Regulated Assembly to vote for war/peace, choose archons
B) Cleisthenes (508 BC)

Not everyone liked Solon. There was some social tension at the time of Solon.

In 510 BC, the people were pissed off with the tyrants and kicked them out.

Some Greek elites who were previously exiled returned and argued for aristocracy. In some Greek states, when they eliminated the tyrants, they would go back to an aristocracy. In Athens, however, they went to a democracy, as per Cleisthenes

The Spartans came and helped fight for aristocracy. However, the common people rose up and drove the Spartans out, allowing Cleisthenes (and democracy) to come to power. He brought lots of reforms:

  1. Tribal system
    • Athenian society had elites and commoners, traditionally, but also 4 tribes.
      • These were ancient divisions, housing both elites and commoners. However, elites probably dominated. These tribes were mostly geographically divided
    • 10 new tribes which disrupted traditional elite power structures
      • Basic unit was a deme, a neighbourhood of Athens or a village in the countryside (150 in total)
        • These demes were arranged into 30 trittyes (thirtieths) of roughly equal size
        • These trittyes were assigned to three zones depending on the geographic
          • The coast
          • The city
          • The inland
        • One from each zone was assigned to each of the new tribes
    • This tribal system replaced the traditional four-tribe system
  2. Deme structure: training ground for politics, demotic naming, citizenship recognition
    • People were normally named after their fathers. After Cleisthenes, they identified themselves by their demes
      • The old way was too engrained, so this new demotic naming didn’t really catch on.
  3. New Boule of 500
    • Seems like a reworking of Solon’s council, but more demographic
    • 50 formed a prytany at all times (10 a year)
      • If there’s not someone ready/available, then the Areopagus would take over the case.
    • Responsibilities included foreign affairs, finances, and probouleumata
      • probouleumata refered to the topics and decisions that were to be discussed in (and on behalf of or for the) the assembly
  4. Assembly (supreme)
  5. Ostracism
    • There’s no real evidence that any ostracism occured until the 480 BCs
    • to thwart a potential tyrant; as pressure valve for inter-elite competition
      • In the spring, the assembly would vote on whether they want an ostracism. People would vote one way or the other.
        • Theoretically, if people felt that there was too much tension, or an elite was getting too excited, then they would vote for an ostracism
        • One of the ostracons would have a person’s name engraved on it. This person, upon voted on, would have to leave Athens for 10 or so years. This allowed Athens to eliminate potentially dangerous shit.
    • This demonstrated the power of the democracy over the elite
C) Generalship (Strategoi) in 501 BC

Typically, a magistrate led the military. Every year, 10 general were elected, and, around 490 BC (Battle of Marathon), the polomarcs became ceremonious positions. As democracy grew, these generals started leading the military.

Even though the archons were higher level, the generalship was more important and powerful. These generals needed to be skilled and proven. The generalship became the most important magistracy

Generals were consistently re-elected. Some generals included:

  • Cimon (470s and 460s BC)
    • Very skilled war general. Held a generalship position for many years
    • However, was not great politically, and was exiled
  • Pericles (450s, 440s, and 430s BC)
    • Generalship was a bit iffy, but was very political. Was very influential in the assembly.
D) Diminishing of Areopagus

Areopagus was still the most prestigious government body. However, people (like Pericles) wanted to make democracy more radical. As such, they attacked the Areopagus

  • In 487, they began electing the archons by sortition. This led to a loss of prestige
  • Reforms of Ephialtes (462)
    • Many powers taken away from Areopagus
    • Was this a true democracy now? There wasn’t a grand body to make the decisions, and the body was elected by, essentially, the people (through democracy)
      • The Areopagus was used as a last decider for certain pieces of law. This power was strigged from them
      • The judicious power was also taken, and given to the boule
    • Murder and maim trials were still held by the Areopagus
    • Ephialtes was assassinated shortly after.
      • Pericles took over as the radical democrat
E) Pericles
  1. Archonship opened to everyone (though technically not to thetes)
  2. Pay for service (jury duty, Boule, then assembly attendance)
    • Poorer commons who couldn’t afford to not work for a day were now paid for jury duty
    • Boule members who were on duty 24/7 were paid
    • Again, workers couldn’t take a day off work to attend assembly. This encouraged people to contribute their voice at no consequence
      • This was kind of scandalous at first, but serves to demonstrate how radical the democracy was.
F) After 403 BC

After the Peloponnesian War, the Athenians weren’t doing well. The radical democracy was blamed for their issues, and intellectuals like Isocrates and Plato critized it.

In 411 BC, the assembly voted itself (the democracy) out of exisence. They returned to an aristocracy, but it was rather unsuccessful (understatement?), and so Athens returned to a democracy.

At the end of the war, the Spartans set up an aristocrat council of 30. This council was so evil and destructive, that it convinced the Athenians to avoid aristocracy completely. Still, it was questioned by intellectuals named above.

This democracy was not questioned until the Macedonians took over.

CLAS201, 2017-05-17

SPARTA

Intro: Reality and Mirage

A) Issue
  1. Reality
    • A truly remarkable state
  2. Mirage
    • An ideal state of laconizers and philosophers
      • In many states in Greece (in classical times, in Athens), there were laconizers (i.e. Sparta-lovers). These people thought that the Sparta-way was superior and ideal for every Greek state
      • During the Peloponnesian war, there were groups that were so pro-Sparta that were they an internal threat to Athens
        • Most famous laconizer in Athens was Critias
      • Most of the survived writing is from Athens.
        • Most historians from Athens say that the Spartans had the ideal state(?)
B) Basis of Mirage
  1. Sparta’s relatively closed society
    • Many people go to Athens for different reasons. Economic, political, etc. It was on the sea and it was an economic power. It was a democracy, and considered a hub for the region.
    • The Spartans, on the other hand, was quite the opposite
      • Sparta was not a hub of trade, nor intellectual endeavour, nor artistic endeavour
    • Historically non-talkative
      • Laconic: “From the territory of Laconia”, also meaning non-talkative
  2. Sparta’s uniquely focussed austerity and militarism
  3. Virtually no Spartan sources
    • There were many historians who wrote about the Spartans. For example, Herodotus who documented the Persian war. He was from Halicarnassus and probably never visited Sparta
    • Xenophon joined a Spartan army in Asia, and became a friend to the Spartan king. Spent 20 years in Spartan territory and wrote a lot about the state. He seems very idealistic about Sparta
C) Humble’s Caveats
  1. Strict militarism
    • Every citizen had the obligation to contribute to the well-being of the state. Perhaps even deprive one-self for the sake of the state
      • The primary way to contribute is to be a soldier to defend the state
  2. Shadow of the Helots
    • Helots were serfs that the Spartan economy was based on
    • Had a few meager rights. Had to produce food for the Spartans. Sparta mobilized itself militarily because they were always afraid that the Helots would revolt

These points serve to add some caveats as to why Sparta was so highly militaristics.

I. DEVELOPMENT OF THE STATE

A) Synoecisms: 4 villages & Amyclae (800 BC)

Instead of colonizing, Spartans just conquered the villages near them.

B) Expansion in Laconia (first half of 8th century BC)
  1. Territorial Expansion in Greece (instead of Colonization?)
    • though, cf. Taras/Tarentum
      • There was a group of disenfranchised Spartans (of illegitimate birth). These people couldn’t be full Spartan citizens, so the state told them to go form a colony of their own overseas
        • This was a colonization for political reasons, it seems
        • Caused by a group of people who were not full citizens but felt they should be
          • This was a commonly occurring issue. Sparta seems to restrict citizenship
C) Expansion in Messenia

Roughly by 750 BC, Sparta had conquered the entire southern portion of the Peloponnesus (and more). And so, they went over the mountains to the left of the Laconia. The Messenian territory had rich lands.

  1. First Messenian War (740-720? BC)
  2. Second Messenian War, after the Battle of Hysiae
    • Once Sparta had conquered Messenia, they had to go north, notably Argolis (to the north-east of Laconia)
      • main city: Argos
      • It looked like the Argos resisted (they were traditional enemies)
    • The Battle of Hysiae (a loss against the Argos) ignited the Messenians to rebel
      • The counter-action against this revolt took decades and lots of resources
    • After the Second Messenian War, the Spartans decided that in order to keep their conquered land (which was a relatively large territory), they’ll need to focus on their military.
      • They made their full-time citizens into full-time professional soldiers
        • They could do some shit with the hoplite phalanx that other states didn’t think possible.
        • They drilled their military almost 24/7(?)
        • Nowadays, scholars don’t think this was the entire reason to go strict militarism, but oh well.
D) Resultant Configuration of Spartan Society
  1. Spartiates
    • full Spartan citizens, dedicated to support the state, esp. in war
  2. Perioeci/Perioecoi
    • dwellers-around the Spartans, locally independent but subservient to Sparta
      • craftsmen and traders
      • had local government, but whatever the Spartans needed, these Perioeci would do what was asked. This mainly consisted of mobilizing for war.
    • Xenophon told a story about his Spartan King. The Perioeci were a little cheezed that they sent more units or did more work. The Spartan King then noted that Sparta brought more actual soldiers (not cooks or blacksmiths) than the Perioeci did, and so did more of the fighting.
      • This story was reflected in 300, between King Leonidas and the Arcadians
  3. Helots
    • Serfs who worked the land of the Spartiates
      • cf. neodamodeis
        • Raised the issue about how rebellious Helots were.
        • During the Peloponnesian war, when the Spartans weren’t doing well, the Spartans enfranchised the Helots and allowed them to become (partial) citizenship and freedom from helotry.
          • Usually had to do with getting them to serve in the military
      • Theucydides story
        • Even while the Helots were Helots, they’d be brought along with their Spartan masters. The Helots would potentially outnumber the Spartans 7 to 1.
        • At one point (in the story), the Spartans said to the Helots “how many of you think you’ve served more bravely?” A few hundred stood up, and the Spartans slaughtered them.
          • Part of the story that the Spartans would always worry about the Helots revolting
          • So, they killed the boldest ones
          • Whether this story was true or not is an open issue.
    • Were allowed to own their land, and couldn’t be sold away, but contributed produce to Sparta
    • Compeltely subservient to the Spartans
  4. Hypomeiones
    • a shadowy group of Spartans who were not full citizens. Participated in their military like anyone else
      • “the people who were under”
    • e.g. Cinadon
  5. Nothoi
    • bastard children that were not automatically Spartan citizens (and probably had no way of becoming such). Still, were considered Spartans
    • These people (and Hypomeiones) argued why they weren’t considered Spartans. They felt it was unfair, and this was a common problem in Spartan history

Helots v. Perioeci

  • No real way of knowing for sure how Spartans decided

II. GOVERNMENT

A) Kingship

Greek poleis had a “king magistrate”. He didn’t function like a king, but there was a position that was called “king.” It was just a yearly magistracy.

Only Sparta had true kings. However, Sparta was not a monarch… because they had two of them.

  1. Dual
    • Agiad and Eurypontid kings from early days
      • two branches of the kingship
      • don’t know where they came from
        • speculation: two main chiefs from the first amalgamation of Sparta
        • Herodotus had a good story about the origins of their kingship
          • at one point, early in Spartan history, a king had two sons. The officials asked, “who was born first?” But they couldn’t tell them apart. The mother didn’t know either, but maybe she did and she just didn’t want to say. So, they made them both kings.
          • After the proclaimed both kings, they saw that the mother favoured one slightly more, and made that king have the more honourable kingship
          • No scholars believe this
  2. Function
    • Mainly military leaders but also had religious and judicial duties
  3. Limitations
    • Had to negotiate with ephors and swear to uphold the constitution
B) Gerousia
  1. Composition: 30 men over 60 years old, elected by the assembly. This included the two kings
    • In Sparta, the practical power was the senate/Gerousia
    • It’s more like the assembly confirmed it (rubberstamped it)
  2. Powers
    • Probouleutic
    • Judicial (murder/treason trials)
    • Legislative (regulated laws)
    • Veto: could overrule assembly, by shouts of yay or nay
C) Apella (Assembly)

Theoretically spreme but in practice a “rubber-stamp” body. The assembly is all the citizens together. Though Sparta was not democratic, it had some democratic aspects.

  • In Sparta, it wasn’t necessarily too different from Athens, which did give their citizens lots of power.
D) Ephors
  1. Composition
    • highest magistrates, five elected to one-year terms from any Spartiate 30 years or older
  2. Powers
    • Presided over gerousia and apella, oversaw agoge, restrained kings
      • Later on in Spartan history, often conflicted with kings
    • Some think the ephors were instituted, others think they gained power over time

It occurred to me one day that Sparta, though among the most thinly populated of states, was evidently the most powerful and most celebrated city in Greece; and I fell to wondering how this could have happened. But when I considered the institutions of the Spartans, I wondered no longer. Lycurgus who gave them the laws that they obey, and to which they owe their prosperity, I do regard with wonder; and I think that he reached the utmost limit of wisdom. For it was not by imitating other states, but by devising a system utterly different from that of most others, that he made his country pre-eminently prosperous.

Xenophon, Constitution of the Spartans, 1.1-2 (tr. Bowersock)

  • It’s very unlikely that a single man named Lycurgus came up with the system, but it demonstrates the habit of Greeks to identify one man who did everything
  • Xenophon is very much “othering” the Spartans. Everything they did seemed to be completely different from that of other states

III. SPARTAN EDUCATION

A) Birth

Boys (girls too?) were inspected by officials, and if sickly or weak were exposed

  • This was not actually an unusual practice among ancient Greeks. Ancient Greeks that didn’t want a baby would expose them and leave them to die. Sometimes, people would take the child and raise them for slavery or some such.
    • In Ancient Greece, families that had 6 children might not be able to take a 7th, and so…
    • In Sparta, it was different because it was decided by a group of officials (the state)
B) At the age of 7

Boys were sent to live with age-mates and trained to be tough, resourceful, obedient motherfuckers

  • Stories were that they weren’t fed enough. So, they stole food (being resourceful).
    • They might have been given just a single cloak as clothing to survive by.
  • Younger boys were overseen by older boys
    • No concern over bullying…
  • Xenophon said that it was the duty of the adult to discipline any child, not just their own
C) Adulthood
  1. Syssitia
    • At age 20, they would be elected to a Syssitia
      • people they would eat with and live with. To become a full Spartan citizen, needed to be elected to a Syssitia. If they were weak or not tough enough, could potentially not be elected
        • If not elected, that’s it. Not a full Spartan citizen. Not a full-time soldier.
        • “Inferiors” Cinadon of Sparta
      • Tisamenos of Elis
        • Every Spartan soldier had land that was worked by Helots. From that land they would denote a certain amount of resources. If demands weren’t met, the Spartan was eliminated from the Syssitia
        • It was very difficult to be a Spartan citizen. Even if the child would pass the agoge, they could be eliminated afterwards.
        • Tisamenos was from the Peloponnesus (not Sparta). He went to Delphi and was told he would have 5 victories. So, he decided to train as an athlete. He wins 4 wrestling matches but couldn’t win a 5th. The Spartans figured that Tisamenos would win his 5th victory as a military general.
          • He wanted to be a full Spartan citizen, but was denied
            • He was given citizenship
          • He then asked for his brother to be a Spartan citizen as well.
            • He was also given citizenship. As per Herodotus, these were the only 2 non-Spartans given full citizenship
  2. Marriage
    • At age 20, were encouraged to marry
    • Kind of weird… because they still lived with their Syssitia as this point.
  3. Full citizenship at 30 and now a citizen would set up his household
D) Women
  1. Education
    • Girls were educated similarly to boys, to be strong enough to bear strong citizen-soldiers
  2. Status
    • Women had relatively high status
      • Had a lot of work to do within the household
    • More freedom, outspoken (e.g. Gorgo, wife of Leonidas)
      • Gorgo was told to have advised her king(s)
    • Married later, could inherit property

Only two types of people were given engravements on their gravestone: Soldiers who died in battle and women who died in childbirth.

  • This indicates the status of women (higher than it was in other civilizations)

CLAS201, 2017-05-24

WAR AND PEACE

  • Greeks did have archers and skirmishers, but didn’t really admire soldiers who shot from afar.
    • The truly courageous and noble was one who stood face-to-face against the enemy
    • Portraying the Persians as archers signified what the Greeks felt about them, and how they “other’d” their enemies

Introduction

  1. Psychologically
    • the Greeks viewed war as an integral part of life
      • e.g. Homer’s Iliad
        • Story of war, death, and destruction (Trojan War)
        • The Greeks fought to rescue(?) Helen from Troy
      • e.g. Athena, goddess of wisdom, civilization, and war
        • seems like war is a natrual state of being. Today, civilizations at war seems uncomfortable
        • For the Greeks, the two are united
    • Homer (in Iliad seems to realize war is evil, because he gives lovely expositions of people who died in war (how he grew up, how he lived, how he’ll be missed, etc.)
      • But how Homer portrays battles indicates he also things war is noble and glorious
      • In truth, Homer probably viewed war as “it just is.” Sometimes it’s bad, other times good.
    • Athena is probably the most admired Greek god(dess). She seems to be virtually always positively portrayed
      • She gave wisdom and skill, which allowed people to live in civilized manner in Greek city state(s)
      • She upheld Greek civilization
      • But, then, she was also the goddess of war. Contemporary society thinks war is the antithesis to civilization.
        • The Greeks felt that if you were successful in war, your civilization will be successful. Moreover, your civilization can also grow upon conquering other lands in war.
  2. Practically speaking, the Greeks did seem to be always at war
    • it was a constant given the fierce independence of poleis and the shortage of physical resources
      • this led to lots of border wars
      • moreover, the Greeks felt the only way to have peace war to have a dominating empire with enough power to control others
    • the natrual state of “non-peace” is a little depressing, but …

I. INFANTRY

A) Homeric Warfare
  1. Chariots
    • We know stories come from the bronze age
    • Homer talked about chariots, and scholars of recent times think that Homer didn’t really get the chariots thing right
      • Homer didn’t have chariot cores lined up against each other, which was how they were typically used in ancient times
        • He had them in battles, but only used to convey/rush soldiers into the battle
        • So, scholars think the Greeks of Homer’s day had forgotten how chariots were used
      • Still, upon studying Mycenaeans more deeply, it’s unlikely they used chariot cores in actual battles (as Middle Eastern civilizations did).
        • Mycenaeans didn’t have smooth lands to use chariots in
        • Still, literature from the times did talk about some chariots, but it probably only represented status (for Kings etc.), rather than war units.
          • Kings rode in chariots to indicate high status to other civilizations
  2. Individual Combat v. Serried Ranks
    • Late Dark Age, early Archaic Age
      • Individual combat was prominant (could see this in the movie Troy). Soldiers like Ajax were dominant in these single combats
        • this predated the hoplite phalanx
    • Later on, Greeks fought tightly packed. So close that their helmet feathers ruffled each other
      • Not a hoplite phalanx, yet, but a closely packed phalanx
B) Hoplite “Revolution”
  1. Origins
    • Some brilliant Greek came up with the idea of a hoplite shield
      • These shields requisited another soldier to protect his adjacent soldier’s right-hand side
      • This revolutionzed the way of fighting
        • Now, scholars have swung to the idea that the Dark Age and early Archaic Age did in fact fight closely idea. The hoplite shield only improved/refined their combat (rather significantly, no less)
    • Recall the Spartans lost rather badly to the Argos in the Battle of Hysiae
      • This loss was attributed to the Argos developing the hoplite phalanx shield
      • Scholars seemed to pinpoint the hoplite revolution to 669 BC, during the Battle of Hysiae
        • Still, there’s some skepticism because the apparent developer, Pheidon II, was a sketchy character
        • With that said, sometimes stories become popular because they sound nice, not because they made complete sense or because they had distinct evidence
  2. Nature
    • Panoply
      • Hoplon shield, long spear, short sword(?), helmet, breastplate, greaves
        • it seems later on, the Greeks went to a heavy linen rather than a breastplate. They had a shield, so why bother with a breastplate?
        • Still, in Ancient Greece art, Greeks were completely clothed (so as to “other” the enemy, who was usually portrayed as a savage)
    • Tactics
      • Pushing and stabbing in formation until one side breaks ranks
      • cf. highly trained Spartans
        • Spartans, since they trained 24/7, had all kinds of different tactics that other Greeks couldn’t hope to develop
        • Spartan mothers told their soldiers “with it or on it.” Referring to never running away (dropping your shield and running)
  3. “Ritualized” warfare
    • Position of honour, victor sets up trope, truce with the defeated to collect bodies of fallen comrades
      • The winning side is the one left standing on the field
        • This leads to some confusion…
        • The winner sets up a trope (a “turning”). When you make your enemy turn around and run, that is a “turning.” And you set up a monument for the fact that you trope’d them.
          • this usually involves the arms of the loser (actual delimbed arms?)
    • Right wing was position of greatest importance
    • Left wing was position of second greatest importance
    • Centers are the people in between
    • The Greeks didn’t arrange themselves based on skill or possibility of success, but rather by honour and status/respect.
C) Cracks in the Phalanx
  1. The rise of the peltast
    • Iphicrates and the Battle of Lechaeum (390 BC)
      • The Phreciens wore light armour, and was quick. This made them effective in certain situations
      • After the Peloponnesian War, everyone were allies of the Spartans. After a while, people became upset with the Spartans and defied them. In the 390s BC, Athens and Thebes fought against Sparta
        • Most of this fighting took place around Corinth
        • The Spartans controlled the port of Lechaeum
        • Her enemies controlled Sparta(?)
        • Unfortunately for the Spartans, it was the time of festivals, and the Amyclaeans went home
      • Iphicrates took some Greeks and started pelting the Spartans with javelins.
        • Just a handful of the 100s returned home, and the Spartans realized their hoplites were failing
          • Greeks just began hiring Phreciens to throw javelins and started defeating Spartans
          • Sending cowardly peltasts after our noble soldiers… but it worked, and the ritualized aspect of warfare was starting to break down
  2. Theban innovations (370s and 360s BC)
    • From 371 to 362 BC, the Thebans were the most dominant state in Boetia.
      • This was due to a number of brilliant leaders (militarily)
    • Battle of Leutra (371 BC)
      • Thebans loaded up the left side with the best soldiers
        • 50 deep against the Spartans
          • the Spartans had their most honourable troops on their right side. This was countered by 50 deep of the Thebans’ best soldiers. The Thebans fought to win, not follow conventions
          • Moreover, the Thebans angled their front so that their right side (their weaker soldiers) were a bit behind.
        • The Thebans crushed the Spartiates, who were found on the right side of their phalanx.
        • It was a daring tactic (to defy conventions), but it worked
          • Good example of how civilizations tend to limit themselves in war.
          • Their rituals prevented them from fighting at maximum effectiveness. The Thebans essentially rejected that to achieve victory
    • Sacred Band: new motivation and training
      • Thebans had 300 troops who were highly motivated due to their pairings with their higher-age mentors
        • these troops’ relationships were homosexual, and inspired higher devotion
D) Macedonian Phalanx
  1. Origins: Philip II (359 BC)
    • This is during the Greeks’ fighting each other all over the place
    • In 359 BC, Philip II comes to the throne
      • For two years, Philip lived among the Thebans and their military innovations as a hostage
        • note, hostages weren’t treated poorly then. He was a hostage based on the Thebans’ requesting hostages upon their victories. In reparation, the defeated would send hostages
  2. Panoply: helmet, small shield, and sarissa (18 ft. pike).
    • The sarissa was a highly long-range weapon. This led to different formations, hence the new Macedonian Phalanx, where up to six rows of soldiers had their spears pointed in the front.
  3. Tactics: phalanx with calvary
    • Philip II developed a crack-core of calvary. The right side of the phalanx would have a troup of calvary that awaits any break in opponent phalanxes.
    • The calvary would smash the opponent phalanx further, and this was an entirely new way of fighting and was very effective
      • The question: was this really a better way?
        • This was more technologically advanced, but there’s no realy way of saying it was better than the traditional hoplite phalanx
    • This tactic really helped suplant the Greek hoplite warriors
      • It didn’t replace that tactic completely, but was more effective
  4. Dominant until it met the Roman manipular legion in the Helennistic period
    • Philip II used it, and his son Alexander the Great used it
    • cf. Pyrrhus of Epirus (280-275 BC)
      • “Pyrrhic victory”: a victory with catastrophic losses
      • When the Greeks met the Romans, they lost so much of their troops, but was still somewhat successful. Still, the Romans were so relentless that any Greek victory would be met by large losses.
    • The manipular legion was more flexible, especially in tough terrains
      • The Romans left more space in their phalanx

II. NAVY

Based on the trireme

A) Origins

Developed in Egypt of Phoenicia (Corinth?) in 6th century BC.

B) Nature

The Greek navy consisted of (mostly) triremes.

  • Long and narrow, made for ramming
  • 170 rowers in three banks
    • Large number of rowers meant the trireme was effective at turning
    • note, triremes had sails, but they were only used to get to battles, and were removed during them
  • few marines (10)
  • archers (4)
C) Naval Tactics
  • Periplous
    • Lining the perimeter like a phalanx
    • Ships would be lined next to each other, separated by enough space for oars to not crash into each other
  • Diekplous
  • Forming a circle

The last battle of the Peloponnesian War

General Conan

  • Tried to war the other Athenians (who didn’t listen)
  • Sailed out with some ships, and managed to go around the Spartans towards their shore, and stole the Spartans’ sails and sailed off to Cyprus

III. Diplomacy and Peace

A) Alliances
  1. Peloponnesian League (ca. 550-366 BC)
    • Lead by the Spartans
  2. Delian League (ca. 477-404 BC)
    • The Athenians
  3. Various Koina, esp. in Hellenistic era (Aetolian, Achaean)
    • These Koina were originally ethnic-based
    • Once the Greek kingdoms were established, it was difficult for individual Greek cities to stand alone.
      • After 323 BC, the Koina became powerful and important, so as to defend themselves against the threatening Greek kingdoms
B) Diplomacy
  1. Ambassadors were sacrosant
    • These ambassadors were protected by the gods, and not to be touched
    • NB. Sparta and Athens mad disrespect against Persian ambassadors (490 BC)
  2. Proxenia (and Proxenos)
    • originating from “Xenos”, ambassadors protected by Zeus
    • Citizen representative of a foreign power.
    • e.g. Spartans want their interests to be upheld in other states (like Embassies would do)
      • Spartans wouldn’t send an ambassador to Athens just to argue their case. They’d have someone permanently in Athens looking after Spartan interested. These individuals would be called Proxenos
        • e.g. Cimon for Sparta
        • When ambassadors from Sparta came to Athens, they’d stay with Cimon and discuss the politics of the situation
        • Naturally, these Proxenoi are susceptible to ire from the state they live in. This meant they garnered some prestige and status.
C) Peace Treaties
  1. Specific peace treaties
    • e.g. Thirty-year peace between Athens and Sparta (446-431 BC. Note the math).
  2. General/Common peace
    • e.g. King’s Peace, 387 BC
      • Agreed to by most of the Greek city states
      • Basically, everybody was allied with Sparta after the Peloponnesian War (404 BC). Thebes and Corinth then broke away, and started the Corinthian War (Thebes, Corinth, Athens against Sparta)
        • This war dragged on for a while, and when the states were ready for peace, they gathered in Persia.
        • At this point, it was determined that the Greek states would be independent, and Persia oversaw the states that broke the peace.
      • Didn’t last very long.

CLAS201, 2017-05-29

Law and economy will be on the midterm, but not covered in class. Read the chapters in the text.

  • From chapters in the textbook: Law and Justice, and Economy

ANCIENT GREEK RELIGION

Greeks didn’t really have a word for religion (Robert Garland). They had a word for “fear of (the) god(s)”, but that’s not really the same thing.

I. THE GODS

Greeks were influenced by Homer and Hesiod in terms of the way they thought about the gods. They sort of had a bible, but it didn’t have the authority as you’d expect.

A) Polytheistic
  1. Major gods embodied natural and cultural realities
    • e.g. Zeus (sky), Poseidon (sea), Demeter (fertility), Aphrodite (fertility), Athena (civilization, war), Hephaestus (fire, craftsmenship)
  2. Minor gods inhabited every tree, spring, and river
    • 3000 or so
B) Powerful and Glorious
C) Anthropomorphic

With foibles and pettiness

  • e.g. Zeus’ infidelities, Hera’s suspicions and shrewishness, the violence of Mars (Ares?)
D) Immortality

This is the highest distinction between gods and humans

  • Note the indifference of the gods to human suffering in Iliad
  • “Know thyself”
    • Not meaning “to understand own abilities and own foibles”
    • Know that you are mortal, and that you will die, and live accordingly
E) Scepticism About the Gods
  1. Critiques of anthropomorphicness of gods
    • Xenophanes (b. 570 BC): “One god is greatest among gods and men, but his appearance and thought are nothing like ours.”
      • May have been monotheistic
    • Plato would exclude poets from his ideal city because of their immoral view of the gods
      • Felt that these poets filled peoples’ minds with nonsense about how bad the gods were
    • Nevertheless, these people (any people who criticised gods) are not atheists.
      • Atheism was “a step too far” back then
  2. Agnosticism
    • The sophists questioned traditional views
      • e.g. Protagoras said, “Man is the measure of all things. … Concerning the gods, I have no means of knowing whether they exist or not or of what sort they may be. Many things prevent knowledge including the obscurity of the subject and the brevity of human life.”
        • This quote suggests a level of agnosticism, but he questions how we could know anything about them
        • Though he does mention that they do exist
  3. Atheism was rare, but
    • Diagoras of Melos
      • was a defiant atheist
      • Story of the storm: as ships traveled through a storm, sailors believed the gods were targeting Diagoras
    • Epicureans
      • felt that there was no eternal soul and no intervention by the gods
        • they felt that it was impossible for the gods to intervene with humans’ actions
        • soul was made up of tiny atoms (as opposed to big ones…). When you die, your body dissolves quickly, but the soul dissolves slower
      • practical atheists

II. PRACTICE OF RELIGION

A) In the Household
  1. Zeus Ktesios (of property)
    • a two-handed jar. Filled with food to garner protection
  2. Zeus Herkeios (of the fence/wall)
    • protects the house from bad things. Pray to this little manifestation of Zeus
      • Once a year, a festival for this god
    • Instead of “Where do you live?” you ask, “Where’s your Zeus Herkeios?”
  3. Apollo Agyieus (of the street/road)
    • manifestation of Apollo
    • turns evil things away from your home. He watches from within but also around
  4. Hestia (the hearth)
B) In the Village/Neighbourhood (deme)
  1. Example of deme of Erchia
    • 25 festival days (total of 59 animals sacrificed)
      • to six Apollos
      • seven Zeuses
      • and heroes (three unique to Erchia)
  2. Especially agricultural festivals
    • tributes to Demeter (Thesmophoria, secret rites for woman only)
    • and Dionysus (grape festivals, Dionysia with revelling and dramas)
C) State level
  1. State religion reflects household and deme religion
    • e.g. Hestia altar at Prytaneion Zeus Herkeios altar on acropolis
    • e.g. Greater Dionysia, all served by state-sponsored priesthoods (incl. 40 for women)
  2. Eleusinian mysteries
    • for those who choose to be initiated; open to any Greeks; for a happy afterlife
    • to Demeter, but not to do with the fertility of the soil, but rather having a successful afterlife.
    • In most cases, to fully participate in a festival, you had to be a full citizen of the state it’s held in, or at least had to live there.
      • The Elusinian mysteries were open to any Greek
    • Nobody knows what kind of revelation was found at the end
      • But, supposedly, it changes peoples’ lives, because now they know they’ll have a succesful afterlife.
    • “Happy is the one of mortals on earth who has seen these things. But those who are uninitiated into the holy rites and have no part never are destined to a similar joy when they are dead in the gloomy realm below.”
      • Homeric Hymn to Demeter
D) Pan-Hellenic Religious Festivals
  1. Oracle of Delphi
    • consulted by individuals and states
    • cf. Dodona
  2. Olympian Games to Zeus and Pelops
    • cf. Also Isthmian (Poseidon), Pythian (Apollo), and Nemean (Zeus) games

CLAS201, 2017-05-31

HEALTH AND DISEASE IN ANCIENT GREECE

I. MEDICINE

A) Superstition
  • Disease caused by the gods or curses
    • e.g. plague on Greek camp in Iliad
      • book starts in the Greek camp. People and animals are dying in/near the camp. They go to Calcus the prophet, who determines that Apollo is angry at King Agamemnon
        • Because Agamemnon took a woman captive in a raid. It was not abnormal, contextually, to take hostages.
        • However, the family of the taken woman offered gifts and compensation, and the King refused it. He kept their daughter, Chryseis, captive.
        • Apollo then casts a plague on the Greeks
          • this caused Agamemnon to return Chryseis, albeit relunctantly
      • this story shows that gods had much to do with health and disease
    • e.g. plague in Thebes in Oedipus Rex
      • Oedipus becomes King of Thebes, which gets hit by a plague
        • Thebes sends a delegation to Delphi, and Apollo says that it’s due to Oedipus himself, who killed the old king, continuing to live in Thebes.
        • Oedipus needed to be exiled, and poked his own eyes out and exiled himself.
      • The plague was sent because the gods were angry
B) Rise of Medicine
  1. The “rationalist” movement
    • This is seen in writings of natural philosophers and historians
    • In Hesiod’s Theogony, he described a very mythological view of the world and its creation, which came from the gods.
      • This was still systematic, in a sense
      • The idea is that the gods were directly involved
      • It also caused natural philosophers to start thinkin about how the world came to be in a natural way.
        • Water is all around
        • Earth is condensed air
        • Fire is expanded air
          • This seemed pretty interesting at the time, as a counter to mythological explanations
    • In the Iliad, Homer described the war as having intervention from the gods, where Athena and Ares took sides in the war
      • again, this is an unnatural explanation, and some sought a more non-mythological idea
    • Similarly, the beginning of the Minoan civilization involved Zeus impregnating a woman in a cow sculpture.
      • very unnatural explanation to how the Minoans came to be
  2. Hippocratic writings
    • Health was based on the four humours (fluids): blood, phlegm, bile, and black bile
      • if you were healthy, the four humours were balanced
        • obviously, the Greeks had no idea about pathogens, and viruses, so it’s not unnatural to think that they believed these ideas
        • e.g. Sickness with cold and high phlegm means your body had an abundance of phlegm, and the body needed to achieve a balance again
      • solutions like bloodletting can be attributed to these (relatively) primitive ideas of health
        • as far as they knew, this made sense, and didn’t have anything to do with divine forces and godly intervention
    • Effectiveness of medicines: much not effective, but did have effective herbal remedies (e.g. Ephredra) and surgeries perhaps (e.g. Trepanation)
      • Ephredra was used to hemorrhage wounds and cease bleeding
      • Also where we get ephredrine, known to coagulate blood
        • so, it makes sense that these were effective in solving their issues back then
      • Surgery, on the other hand, was only done under very extreme conditions. They didn’t really know what caused infections, so only rarely cut into someone else’s body.
        • When they would, they didn’t really disinfect. Still, the Hippocratic oath talked about avoiding surgeries
      • Trepanation involves relieving pressure in the cranium, which caused brain bruising. They’d bore holes into the skull to release pressure
    • Note that ancient Greece writers like to attribute findings and achievements to a single person
  3. Asclepius, god of healing and patron deity of physicians
    • Superstitious thinking, along with a natural approach to healing
    • Various shrines and temples were dedicated to Asclepius.
      • People would approach and give offerings in hopes of being healed
      • Incubation
        • sick beings would sleep in the wellness area (incubate). Asclepius would appear to you and heal you.
    • Even today, you see a combination of rational and mythological healing
      • e.g. Christianity
        • people may pray to God for healing, while going to a doctor. Maybe they’d pray to a doctor to do well.
        • This reflects Asclepius in Ancient Greece, where he signified a combination of mythological and natural healing.
    • Snakes went underground (lots of powers in the Earth), also shed skin (regenerated)
      • There was the idea that snakes were powerful healers

II. STAGES OF LIFE

A) Childbirth and Infancy
  1. Childbirth and aftermath was dangerous for mother and child because of trauma, infection, and bleeding
    • Childbirth was not very advanced (relatively)
    • Mother’s immune system was weaker, and made her more susceptible to infection. The baby’s immunity doens’t develop for a few weeks, so there’d be lots of deaths due to infection
    • Very possible for a child to survive after childbirth, but then set out to die for various reasons
      • e.g. families who could not afford an additional child
      • e.g. Sparta, who casted out deformed/weak children
  2. Note, also the danger of exposure for a child, esp. those with deformities of any sort
B) Childhood
C) Adulthood
  1. Infectious diseases were common, esp. in crowded cities
    • cf. Athenian Plague (430 BC)
      • Right at the beginning stages of the Peloponnesian War
      • Pericles had convinced people from all regions of Greece from the fields and coasts to join in the city
        • and be protected by Athenian wall
        • this meant many more thousands than normal were crowded behind the walls, and the effects of the infectious disease was exacerbated
          • note, scholars don’t know the actual disease
      • Theucydides described the plague in detail (he had caught it as well)
        • Everyone who got the plague was immune to it the following year
        • It afflicted the Athenians in annual waves, over 3 years
        • Said it didn’t matter if you prayed to the gods. The good people weren’t any more immune to it than the wicked
          • He was very doubtful of the attribution of health and disease to gods
  2. Environmental issues, esp. smoky air from home and factory
    • esp. Blacksmiths
      • Craftsmen in bronzemaking factories (with furnaces, etc.) were oft exposed to poor air
      • Note that the Greeks didn’t think noble citizens were to be craftsmen, though the occupation did require skill
    • Homes had hearths, which added unhealthy air to poorly ventilated homes
  3. Lifespan
    • 50 (women)
    • 60 (men)
      • Men were generally treated better. They had better access to food and water, etc.
    • Sometimes much longer
      • e.g. King Agesilaus
        • died around 84 years old, as he returned from a campaign in Egypt

CLAS201, 2017-06-05

STATUS AND CLASS

Introduction

A) Status Categories
  1. Citizens
  2. Metics
    • Definition
      • not just foreigners (xenoi), but resident aliens (metoikoi)
      • needed to register and have a citizen patron
    • Rights
      • no political or property rights but could run a business
    • Responsibilities
      • metic tax, military
      • could receive special grants: freedom from metic tax, property rights, rarely citizen rights
        • e.g. Lysias in 403 BC

CLAS201, 2017-06-07

SLAVERY

I. SOURCE OF SLAVES

Raising slaves on your own

  • The children of slaves would be born into slavery, though this doens’t seem to be the common way to get slaves in the Ancient world
  • Slaves were an economic factor
    • If raising slaves was not monetarily efficient, then it wouldn’t be benefitial
  • Slaves could be bought for specific tasks, like for certain skills
  • Slaves found in slave markets often came from raids
A) Purchasing Slaves
  • Purchased slaves far outnumbered home-born slaves
  • Originally obtained by raiding, trading, and capturing cities in war
  • Raiding was a prime component in gaining slaves
    • Plato himself was almost a slave
  • During the Delian League, as the Athenians became more oppressive to their “allies” and subject states, they would take cities, slaughter the men, and take the children for their slave market
    • Near the end of the Peloponnesian War, the Athenians were afraid that their enemies would do onto them what they did to their captured cities.
      • When the war ended, the Spartans were remarkably lenient. Disband the navy and tear down the longwall and all was good.
      • Corinth and Thebes (allies of Sparta at the time) were upset about that
B) Greeks v. Foreigners
  • It was not considered right to enslave Greeks, so most slaves were barbaroi
    • Thracians, Scythians, Phrygians, Phonoecians, Ethiopians, etc.
    • Still, supposedly 30% of slaves sold were Greeks
  • Note, the Greeks like to dichotomize things
    • Free and slaves; Greek and barbarian (barbaroi, or more generally, non-Greek); Rich and poor;
      • The Greeks liked their slaves to be barbarians/non-Greek

II. SLAVE LABOUR

A) Unskilled: mines, fields, factories
  • Most scholars think even the well-off farmers had slaves
  • There’s some debate, but it seems that only the poorest farms didn’t have slaves
  • Maybe 20-50 workers in a factory
  • Female slaves would work with wool and linen
B) Skilled: craftsmen
  • Blacksmiths, Silversmiths, Goldsmiths, etc
  • Often worked with owners and other free workers
    • A little problematic, since the Greeks wanted to make the distinction between slaves and free.
    • So, free workers didn’t really want to work for the same person as a slave
C) Highly skilled
  • Traders, bankers, managers, physicians
    • Traders would travel on behalf of their owners
    • People wouldn’t naturally hire people to manage their farms, because it might be too close to slave work
      • so, they’d choose a rather smart slave(s) to manage their estate
  • Often with special privileges
    • Often lived on their own, and lived like free people
    • This wasn’t common
    • These slaves could sometimes have whole families
      • However, their children and family could be sold away as slaves at any time
    • It’s worth noting that if these slaves have families, they could be seen as leverage
      • A skilled slave acting as a trader/merchant could just run off with the goods, but not if their families were stil back home
D) Domestic
  • Esp. nurses, who could be treated with great affection
    • The mother of the child doens’t raise the child on a day-to-day hands-on basis.
    • So, they’d have a slave who would nurse the child
  • There are inscriptions that suggest warm relationships between the nurse and family
    • Typically, slaves would be buried in meager ways. However, these nurses would have gravestones and inscriptions in which they were affectionately described
E) Public Slaves
  • Scythian archers, public administrators for administrative continuity

III. IDEOLOGY OF SLAVERY

A) Dinstinction between slave and free was not “somatic” but “psychic”

Psychic refers to “having to do with the soul”

  • In other Ancient times, you could identify slaves through the colour of one’s skin, which would refer to a somatic difference
  • For the Greeks, they didn’t have some physical differences, so they identified slaves by their inferior soul
  • The Old Oligarch was complaining that you can’t tell the difference a free person, a metic, or a slave
    • Because there were so many poor free people
    • If you get slighted by someone, you can’t hit them because you couldn’t tell what status that person was

IV. MANUMISSION

  • Slaves could run and get away with it
    • Pancleon, for example
      • Looks like he could have been a slave, but managed to pass himself off as a free Plataean
  • Slaves could be set free with obligations to their old master
    • Status would be changed to metic
    • These slaves would still be obligated to vote in favour of their old masters
    • Didn’t happen often for the Greeks, but did for the Romans (by the thousands)
      • the Romans had so many slaves, so they simply let some go, and these slaves because citizens
  • Sometimes, masters allowed slaves to buy their freedom

GENDER AND SEXUALITY

Introduction; the problem of sources
  1. Literary
    • Almost entirely from (elite) males except for Sappho (ca. 600BC)
    • Don’t have women talking about their own experience
  2. Art
    • Less elite but both producers and consumers were male
      • poets and writers were writing from the elite position as well as the free male position.
    • Women on vase sculptors, for example, were drawn by men
    • Consumers referred to the people who bought the art
      • This art was (primarily) bought for drinking parties, for the symposium
      • The males bought this art for their male-only drinking parties
      • A respectable free Greek woman would not attend a symposium
  3. Material remains
    • personal items and gendered space more equally perserved
      • archeologists can find tools/items used by both men and women
    • There are portrayals of other groups in the Ancient world who don’t speak for themselves
      • We don’t have direct sources from the Spartans themselves
      • It’s more or less the same for women

I. GENDER

A) Constructionism v. Essentialism
  1. Constructionism
    • Ideas of gender are socially constructed (explicitly and implicitly)
  2. Essentialism
    • “Men and women have different natures innate to their biological identity”
      • Glazebrook, p.268
B) Gender Construction
  1. No spectrum in ancient Greece
  2. Traditional
    • Male: the virtuous sex
      • dominant, active, rational, self-controlled
      • eg. art: nudes, muscular with small genitalia
        • this is in constrast to the satyrs, half-man half-beasts who would have large genitalia and are always aroused, indicating a lack of self-control and rationale
    • Female: inferior
      • passive, submissive, irrational, lacks self-control
      • eg. art: females are covered with clothing
        • cf. hysteria from the Greek word hystera (womb)
          • hysterical: out of control
      • eg. humour of Aristophanes’ Lysistrata & Ecclesiazousae
        • Lysistrata was a play about an Athenian priestess who organizes a riot with the women of Athens and Sparta (during the Peloponnesian War) and goes on a sex-strike until peace is achieved
        • cf. Clytemnestra and Antigone
          • Clytemnestra is portrayed as a very strong woman in the story in which she wraps Agamemnon in a bathrobe and slays him with an axe
            • She takes the role of a man, basically
            • This is a horror story
            • She is killed by her son in the end
          • Sophocles portrays Antigone as a very strong woman who is remarkably positive figure
            • What is he trying to achieve?
            • Antigone must bury her family as her duty. However, she must resist the decision of King Creon who decreed it, since Antigone’s brother was outside of the city walls.
              • She goes and buries her brother nonetheless
                • And stands against Creon, even though she’s doing the right thing
              • Antigone dies in the end, like most aggressive women in plays. This “restores” the balance in the traditional view of gender in ancient Greece
              • She is banished to a cave to die in hunger
                • Instead of succumbing to her slow death, she hangs herself.
              • Her fiance comes and opens the cave. He sees Antigone’s hanging body and kills himself. Note, he is the son of King Creon. Creon’s wife sees her dead son and kills herself, too.
  3. Sophistic: complementarian equality
    • People don’t usually see sophists as subverting societal norms in a good way

II. SEXUALITY

A) Gender Roles
  • Greek sexuality was based on gender roles, not sexual orientation
  • NB. Sexual double standard
    • male: promiscuity was fine except with a married woman
    • female: no heterosexual infidelity allowed
B) Greek Pederasty

Marriage wasn’t about two people falling in love and going through life together, but rather for reproduction.

  1. Stages
    • Eromenos (beloved) as a teen (12-18 yrs)
      • older male would bring a rooster, as a present, to win over the Eromenos
    • Erastes (lover) as a twenty-something
      • the Erastes, with a beard, pursues an Eromenos
      • the dominant partner
      • Zeus himself was portrayed as participating in this kind of pederasty, although it wasn’t common for him in general
        • Zeus would pursue heterosexual relationships outside of marriage
        • The Aristocrats needed some superiority, and this came in the form of being descendents of Zeus.
          • This meant Zeus had to have numerous heterosexual relationships with mortals
    • Heterosexual marriage after 30
  2. Etiquette
    • For the erastes
      • should be a model of virtue
      • should abstain from penetration
        • The Greeks allowed males who weren’t fully citizens (yet) to partially assimilate to the passitivity of the female
      • cf. 50 lashes for a slave who was erastes to a citizen
        • the erastes is supposed to be virtuous and manly, and only citizens could be such
        • The Greeks saw slaves in a similar category as the females, so they could not take the position of an erastes
    • For the eromenos
      • should be modest and hard to get
        • only succumbs to the erastes after seeing his virtuousity and self-control
      • should have no sexual pleasure in the relationship
      • cf. Romans had no such practice(?)
  3. Status
    • A higher form of sexual expression than heterosexuality
      • eg. Plato’s Symposium
        • the topic of the god Eros–the highest form of erotic expression is the love and desire for that which is ultimately good, true, just, and right
      • eg. Harmodius (eromenos) and Aristogeiton (erastes)
        • the two plotted to kill Hipparcus and his brother
          • though they didn’t kill his brother (the tyrant), the story was passed down as if they did, and they were honoured with a double-statue
C) Female Sexuality

We don’t know much about female sexuality because only males wrote literature.

  1. Gender Role
    • passive, and largely secluded
      • kept at home by their families to keep them from sexual relationships
      • eg. poorer families’ daughters would be send out fetching water
        • richer families would send slaves
    • upon marriage, would still be secluded in the house
  2. Lesbianism
    • conformed partially to male pederasty
      • eg. Sappho
        • only female poet to survive from the ancient world
        • shows clear parallels between pederasty and her relationships with her students
        • has poems in which she longs for one of her “lovely” students
        • envious of her young former charges’ husbands
        • Some who have analyzed Sappho’s poems suggest that lesbian pederasty involved a more equal relationship, although there was a clear age difference. Still, the dominant partner is not as clear.
    • NB. Relative silence of male sources points to apathy
      • Males simply don’t care about female relationships

CLAS201, 2017-06-12

LITERATURE AND PERFORMANCE

Literature in the ancient world was experienced mainly in performance, not reading

  • There’s some debate as to what percentage of Greeks in Ancient Athens/Greece were actually literate
  • Similarly, tragic playwrights like Sophocles, Eurypides, were experienced in the Theatre (of Dionysus, perhaps)

I. EPIC POETRY

Homer, Hesiod, Homeric Hymns

A) Oral Development
  1. Iliad and Odyssey were written down after centuries of oral tradition
    • Iliad, about Achilles, his anger towards King Agamemnon, and the Trojan War
    • Odyssey, …
  2. Hesiod wrote the Theogony, regarding the creation of the world
  3. Epic because it was written in an epic meter: Dactylic hexameter
  4. Length of Iliad and Odyssey suggests they were not fully formed until written down
    • Since these epics had accurate references to things in the Bronze Age, they had to have originated from the Bronze Age. They were passed down orally through the Dark Age, and were finally written down later
    • Repetitive nature suggests oral development
      • All these heroes have long names and epithets. These standard, repeated epithets follow the rhythmic requirements for the dactylic meter.
      • These stock phrases that you can fall back on allows you to stick with the meter while also developing what you’ll say next
        • This suggests spontaneous oral composition
    • These two epics were quite long, so it must have been only after writing came to the Greeks that writers could piece these stories into one single epic.
      • However, we have modern day examples of oral poets (from Yugoslavia) who can compose long, complex poems solely in their heads
      • So, it’s tough to say how likely it was that the Iliad and the Odyssey was composed in pieces
  5. Homeric hymns came from a time much later than Homer, but followed under his influences (and the epic meter)
B) Performance
  1. Original Context
    • banquets of the elite
      • in the Dark Age, the elite would hold a banquet for the people. Lots of food to eat and wine to drink
      • then, the elite(s) would hire a bard to sing the songs of the Trojan War, the Odyssey, etc
  2. Later Contexts
    • rhapsodic performances
      • these performers would memorize these epics and hymns and have a competition
        • agonistic
          • work hard to win a competition. Everything was competitive
          • best rhapso, best poet, etc.

II. LYRIC POETRY (ca. 650-450BC)

A) Form: Great Variety
  • Different meters (elegiac & iambic) and musical accompaniments (lyre, oboe, harp)
  • Choral and monodic (solo musician)
  • Topics
    • Love affairs, war, politics, wedding songs, death, athletic victories
    • Lots of complaints about common people crudely invading the realms of the elite
      • these poems would be written by or performed for elites, so this makes sense
    • NB. often very personal
B) Performance
  1. Symposia
    • Elite drinking parties
    • eg. Theognis
      • sounds like a grumpy idiot
      • talks about the “good old days” where everyone knew their place, and how it has all gone to shit
  2. Public
    • partheneia, celebrating young women coming of age
      • could be wedding songs as well
      • maybe sung at festivals held in city states
    • epinician odes
      • a victory song
      • eg. Pindar
        • a great person wins an event at the games, and someone like Pindar would write a victory ode to this person
        • this song may possibly be sung at the games themselves, after Pindar had quickly put a song together for you
        • more commonly sung when the person arrives back home, because the person had brought glory to his city state

III. THEATRE: TRAGEDY AND COMEDY

A) Development

From the dithyramb (choral hymn to Dionysus) under Pisistratus

  • The dithyramb would have fell under the category of lyric poetry
    • sung at the festival of Dionysus, about the great deeds of Dionysus
    • a chorus of maybe 50 men sang the dithyramb
      • led by a choragus, who would step out, be an individual, and address the chorus
B) Important Aspects of Theatre
  1. Religious setting
    • part of festivals to Dionysus
      • Dionysia; things that had to do with Dionysus
      • A greater Dionysia was called the City Dionysia. A big festival that was highly religious
        • The day before the festival began, there’d be a procession of the image of Dionysus (eg. his statue)
        • They’d bring his image out and back into the city, as a way of welcoming him back to the city
        • The first day, there’d be a big parade (with large phalluses…)
          • Feasts and wine
          • Choral arrangements
          • Dithyrambs performed by choruses of 50 men
            • these performances were very competitive
        • The second day, there would be 5 separate comedies
        • The third and fourth/fifth day, there’d be tragedies and a satyr play
          • these tragedies would be terribly depressing
            • catharsis of pity and fear
          • these satyr plays much more lively and upbeat. Farcical and satirical
            • makes a mockery of some Greek myth
  2. Political Significance
    • presided over by the (Eponymous) Archon
      • most prominent political position
      • there was an Archon called the Basileus (the King Archon), who resided over religious things, while the Eponymous Archon resided over political things
      • chose the playwrights to present their 3 tragedies
    • Theoric fund
      • some sources say Pericles brought this in during his radical democratic revolution
        • though some disagree
      • state money given to people to pay for their entrance into their theatrical performance
        • the state felt that both the tragic and comedic performances were for the educaiton of the people
        • the tragic playwrights were called dedascoloids (teachers)
        • people needed to be sophisticated thinkers
          • rule and be ruled in turn; everyone should be involved in politics, which required sopĥisticated thinking
    • Political Issues “discussed”
      • plays didn’t discuss contemporary (for the time) political issues, but rather mythical themes
        • still, these mythical themes always indirectly addressed political issues
      • Tragedy
        • Aeschylus’ Eumenides (ca. 460 BC)
          • this play is about the Areopagus, and a famous hero who had to avenge his father’s death. However, his father’s killer was his mother, and Apollo tells him that he must kill his mother regardless.
          • There is a trial for whether he is guilty or not, and the Areopagus declares that his responsibilities are to his father, not his mother, hence freeing him
          • Significance: Around 460 BC, Pericles transformed the Areopagus by taking most of their powers away
            • Just when people were struggling with this political reformation (of the Areopagus), this play showed it still had the right to try murders
            • This play seems to try to tell people that the Areopagus is still a very important institution
          • Also recall that Ephialtes, Pericle’s partner, was assassinated for instituting this deformation of the Areopagus
          • Aeschylus comes into this controversy and delivers a play regarding the political implications
        • Sophocles’ Antigone
          • This play was put on when Athens was working on their traditional laws
          • Question: How much can you change the traditional laws and still be legitimate, because the gods have established what’s right and wrong?
            • Laws were based on morals established by the gods. If you start changing these laws, when do you go too far?
          • Antigone is about a woman who stands up and does what the gods have decreed at the cost of rejecting her king/the law.
            • Clear political implications here
      • Comedy
        • mostly set in contemporary Athens
        • political leaders directly and explicitly lampooned
        • eg. Cleon and Theramenes
          • Aristophanes featured Cleon quite prominently, and presented him as an idiot.
          • Theramenes was another well-known political figure, and was presented as a simpering fool
        • consider this as precedence for what modern day comedians are doing when they satirize and mock political figures
C) The Plays
  1. Tragedy
    • Mostly mythical themes with contemporary relevance
      • cf. Sack of Miletus by Phyrnicus (492 BC)
        • about how the Persians destroyed Miletus
          • this upset the audiences, and Phyrnicus was fined
      • cf. Persians by Aeschylus (472 BC)
        • related to contemporary issues, and how the Persians lost their final war that dashed their hopes of conquering Greece
  2. Comedy
    • Setting
      • contemporary Athens
        • eg. Lysistrata
          • the sex strike of women in Athens and Sparta
        • eg. Clouds
          • highlights Socrates as a dipstick(?) in the clouds
          • in all philosophical texts, Socrates is wise and humble. Slightly goofy, but profoundly wise
            • yet, Aristophanes portrays him as bizarre, and shows Socrates teaching unjust/strange arguments to win a day in court
          • did not directly address political issues, but lampoons contemporary currents.
            • Socrates is the embodiment of all new thinkers in philosophy, but a lot of people didnèt like that. So, it makes sense to have this sort of comedy against Socrates
        • eg. Frogs
          • Aristophanes pokes fun at the chorus, portraying them as frogs
          • Just recently (to Frogs), both Sophocles and Aeschylus had died
            • People worried, now that the good playwrights/poets had died
            • They wanted one of their poets back, and so Dionysus is comissioned to go down to the Underworld to fetch one of the dead playwrights
            • The frogs sit by the river Styx, and Dionysus is portrayed very satirically
    • Playwrights
      • Aristophanes (450-385 BC)
        • around 11 of his plays have survived
      • Menander (344-292 BC)
        • small amount of his plays

CLAS201, 2017-06-14

ART AND ARCHITECTURE

I. ART

A) Painting
  • Wall & Panel Paintings
    • Greeks did a lot of this, but they didn’t really survive over time
    • Painted on wood or wooden panels
      • Wood tends to rot, and very few wall and panel paintings survived
B) Vase Paintings

Material

  • Pottery vessels many styles and sizes
  • Pottery was curved, which necessitated skilled painters

Development

  • This is much easier to trace than wall paintings, due to their better survival

Geometric (900-700 BC)

  • patterns were very rectilinear
  • lines are in parallel, and even human bodies were drawn with straight lines (like triangles) rather than curves
  • bichromatic
    • two colours: black and the lighter colour of the pottery itself
      • black was done using slip. This solution became black when the pot was fired

Orientalizing (700-600 BC)

  • art is now curvilinear
  • began portraying humans and (esp.) animals, both domestic and wild
  • as well as monstrous compositie animals
    • lions, snakes, roosters
    • some portrayals are mythical
  • polychromatic
  • style originated from Corinth
    • interesting, because Athens was the big location for Geometric pottery
    • the trend had switched to Corinth
    • In the latter part of 700 BC, Corinth became very prosperous due to trade
      • Corinthians made their city a center of trade
      • They were on the sea, had a large fleet of merchant ships, and were also right on the little gap between East and West Greece
        • Ships didn’t want to go around the Polyponnesus, so they docked at Corinth, and the Corinthians dragged these ships across the Isthmus, allowing a shorter and also safer passage
      • This exposure allowed Corinth to stay “trendy”
  • tree of life theme
    • from the East, with mythical symbol

Black-figure (700- BC)

  • Artisans in Corinth developed a new technique called black-figure
    • which spread across Greece
  • painted silhouette and fill of a character with a slip, which turned black when the pot was fired
    • eg. Hericles and the Nemean Lion
  • after firing, the artisan would carve lines within the silhouette. These incisions act as the details/lighter colour
    • can do musculature, etc.
  • around this time, artists began to adapt to the curvature of the pottery in their art

Red-figure (530- BC)

  • Instead of painting the figure of the slip, and firing it like in black-figure, the artist paints the background with slip
  • Details and fine-lines are painted in slip as well, and then fired
  • Developed in Athens. Corinth had lost its dominance by this point
    • Athens dominated trade before Red-figure had been developed
  • Advantages
    • black-figure makes everything look blank (the background would be empty)
    • in red-figure, the background looks “full” because it has colour. It’s a more striking way to present art, since the contrast works for it rather than against it
  • Since the Geometric era, the Greeks had been trying to make their figures more and more realistic
  • Note about realism in art
    • Plato felt realism in art was deceptive, because art is not physically real.

Themes

  1. Orientalizing period
    • floral/vegetal and animal motifs predominated
  2. 7th-6th century BC
    • Athenians began trend toward mythological themes
  3. Late 6th century BC
    • contemporary scenes
      • athletics, symposia, school, pederastic courtship
    • problem of interpretation(?)
      • sometimes, there’d be multiple interpretations and people wouldn’t know which one was “correct”
      • is this a problem with the mythological themes of 7th-6th century BC, or with contemporary late 6th century scenes?

II. ARCHITECTURE

A) Materials

Mud brick and wood until ca. 650 BC, then stone

  • They learned stonework from the Egyptians
    • Egyptians, by this time, had had stone temples for millenia
    • cf. kouroi statues
      • before, Greeks made statues of gods/goddesses out of wood, mostly. Sometimes bronze
      • kouroi (sing. kouros) were statues of males, and looked very egyptian
        • very stiff
        • became more lifelike/realistic over the years
        • not idealized dimensions, but more realistic (and also more fluid, showing movement)
B) Style
  1. Distinctively Greek, with columns and horizontal architraves with low-pitched roofs and pediments
    • between the temple itself and the columns, it’s like porches of sheltered area
    • the columns lined the outside
    • the pediment is the flat triangular section at the end of the temple (above the columns, on the side; the end of the roof)
      • there’d be statues inside this pediment
    • roofs were low-pitched, and so the pediments were relatively flat
    • there’s also some friezes
      • right below the pediment are triglyphs (little columns), that run across
      • the frieze is the running horizontal panel below the pediment that houses the triglyphs
  2. Orders (styles of Greek temples)
    • they all have columns, pediments, and friezes, etc
      • however, some variances can be found among the styles
    • Doric
      • oldest, originated in North-east Peloponnesus, simpler and heavier
      • column height were 6 times the lower diameter
        • looked heavier, and exudes a sense of sturdiness and power
      • had friezes of metopes and triglyphs
        • metopes were empty spaces that probably had relief sculptures in them, but not always
    • Ionic
      • originated from Ionia
      • column heights were 9 times the lower diameter of the column
        • seemed lighter
      • more ornate with continuous friezes
        • eg. Volutes
        • continuous friezes were not divided by triglyphs
      • eg. Temple of Artemis
        • very fancy and ornate. Had some spirals at the top, but we’re not sure what they were supposed to be
    • Corinthian
      • more elaborate and fancier
      • not very important in classical times, so not going to talk about this much
C) Propaganda
  1. Temple of Zeus at Olympia
    • very rich temple
    • monumental chryselephantine statue of Zeus
      • made of chryses (gold)
        • clothes would be pure/gilded gold
      • elephantines (elephant) denotes ivory
        • statue of Zeus was around 40ft tall. The skin of this figure of Zeus would be made of ivory
    • Olympia had the games every 4 years, a celebration of Zeus, who represented overall Greek society
      • the power of the Greeks, civilization, culture, etc
    • served the same function for all the Greeks the same way that the Parthenon (in Athens) served as propaganda for the Athenians
  2. Parthenon
    • Was on the acropolis of Athens, and represented Athenian culture
    • funded by the money from the Athenian Empire
      • represented the impressiveness of Athens
    • glorified Athenian civilization sophistication and power in particular
    • Was rebuilt(?) after the Persian assault of 480 BC, allowing it to represent Athenia victory and power
    • East pediment: portrayed birth of Athena
      • Zeus didn’t want to be usurped
        • a propecy stated he’d be usurped by his son
      • So he swallowed Metis (his first wife) to prevent her from giving birth to his supposed male usurper
      • However, Athena turned out to be female, and sprang from Zeus’ head
        • One version: Zeus had a headache, and Hephaestus smacked his head with an axe
          • Athena jumps out in full armour
      • Athena is powerful because she sprang from Zeus’ head fully armed, and is the embodiment of war and civilization/wisdom/sophistication
        • she was an apt goddess for Athens to choose as their patron goddess
    • West pediment: portrayed the contest between Athena and Poseidon
      • Athens was to choose their patron deity, and had to choose between Athena and Poseidon
      • Poseidon stabs the ground to great a spring
      • Athena plants an olive tree
        • Athenians liked this more, and chose Athena
    • Outside: Doric frieze. The Parthenon also had an Ionic frieze on the inside of the porch, on the walls of the temple itself
      • Story of the Lapiths and the Centaurs
        • Lapiths were a tribe of Greek
        • Centaurs: half human, half horse
        • Centaurs were invited to a wedding of the King of the Lapiths, a friend of Theseus
          • Centaurs couldn’t hold their wine, and went crazy, and tried to steal the bride
          • Theseus (King of Athens) helps the King and the Greek Lapiths defeat the Centaurs
            • The King of Athens helps defeat creatures of anti-civilization
      • The Trojan War
        • Greeks v. Eastern Trojans
          • Trojans represent the Persians, whom the Athenians had just defeated
          • Trojans represent anti-civilization forces
          • Athenians often assimilated barbarians into/as beasts
      • Gigantomachy
        • Greeks were one time threatened by the giants: mindlessly violent monsters
        • Greek gods managed to defeat these, again, anti-civilizing forces (of chaos and destruction of order)
        • Propaganda, again, is that the Greek gods are defeating uncivilization
      • Amazonomachy
        • War between the Amazons and the Athenians
        • When Thesus was King of Athens, he went to the land of the Amazons with Heracles and brought back the Queen of the Amazons
          • they banged(?)
        • The Amazons invaded Athens, but the Athenians managed to drive them back
        • Again, the Amazons were portrayed as a threat to civilization
    • There is also a chryselephantine statue of Athena (the Virgin)

Subtext

These temples and statues all portrayed themes of Greeks/Athenians defending against forces of un-civilization

CLAS201, 2017-06-19

GREEK PHILOSOPHY

I. NATURAL PHILOSOPHERS (PRE-SOCRATICS)

A) New Way of Explaining the World
  • Philosophers were originally called “Fusacois”
    • Naturalists, who tried to explain the world in a natural way
    • These philosophers were reductionists
      • Wanted to reduce everything into the simplest form
      • Figure out the one thing that everything comes from and is made one
  1. Based on rationality
    • The poets were the ones who “knew” about the creation of the world
      • They were inspired by the gods (maybe Apollo, or Zeus), mostly by the Muses
        • Hesiod was inspired by the gods and divine revelation
    • Natural philosophers just looked at the world, observed it, and thought about it a lot
      • Though, modern scientists did more thinking that looking
    • Thales, predicting an eclipse v. Hesiod’s inspiration by the Muses
      • Probably got his information from the East
        • Babylonians knew about celestial movements
      • Thales figured, if you had this knowledge of how the world works, you can predict things
      • The Greeks would say the gods were angry if there was an eclipse, but Thales said this was a natural occurrence
        • Didn’t have to attribute everything to the gods
          • This ideal is the main difference
  2. Critical thinking
    • Natural philosophers would typically write their ideas down, and disseminate them
      • Other philosophers would look at these ideas, and interact with them, and figure out why they might be mistaken
    • Hesiod acknowledged that, sometimes, Muses tell lies
      • There were other versions of the creation of the world that was circulating.
      • Sometimes, Muses don’t give as accurate information
    • Alternate views were debated and critiqued
    • Natural philosophers wrote in prose, suggesting they were not inspired, but rather their ideas came from thinking within themselves

Note

None of these natural philosophers’ work survived. Our only records of them are quotes and explanations of later writers.

  • Thales was esp. hard to figure out
Search for the Arche

Arche refers to some origin, source, basis

  1. Concrete ideas
    • Water (Thales)
      • The world rested on water, and maybe was composed of water
      • Mythical ideas suggest that water is the arche
        • seems like Thales might have been inspired by these ideas
    • Aer (Anaximenes)
      • Aer is the Greek translation of air, but it probably refered to something other than just air
  2. Abstract
    • The boundless (Anaximander)
    • Number (Pythagoras)
      • Pythagoras saw numerical patterns in everything (even when it probably didn’t exist)
      • Not such a weird idea, to be quite fair
        • To understand the universe, we need to understand mathematics and numbers
    • Fire & logos (Heraclitus)
      • “Everything flows.”
        • Heraclitus sometimes sounds profound and wise, but other times sounds strange
          • Very enigmatic
      • Said a divine fire was the arche
        • logos refers to story/orderly narrative
          • suggested there’s some order to the universe
    • Mind/Nous (Anaxagoras)
      • Anaxagoras was an Athenian natural philosopher

Notes

  • The natural philosophers didn’t really get anywhere with their ideas. It seemed like everybody had their own ideas of how the world worked.
C) Change versus Statis
  • Some philosohpers felt that Change was the essence of the universe
    • eg. Heraclitus, “Everything flows.”
      • The universe is in constant change
      • So maybe fire is the arche because it’s active and always changing
    • Parmenides, “Being is all. Ergo, reality consists simple of indivisible, changeless, featureless, rock-solid Being.”
      • The arche has to be “Being”
        • That which is, is
      • Any change is an “illusion”

II. SOPHISTS

A) Relativism
  1. Protagoras
    • “Man is the measure of all things.”
  2. Law/Nature (Nomos/physis) dichotomy
    • conventions have crept into human society as they have tried to organize their society
      • all these ideas that manifest as laws or ethical principles don’t really reflect nature as it really is
      • sometimes, adhering to convention and law goes against nature, and vice versa
    • cf. Slaves, barbarians, women
      • overthrows conventional way of thinking
B) Educational Mission
  1. Practical success
    • wanted to teach people how to live successful lives
    • “What I teach is sound deliberation, both in domestic matter—how best to manage one’s household, and in public affairs—how to realize one’s maximum potential for success in political debate and action”
      • Plato, Protagoras, 318e-319a
  2. Rhetoric

III. CLASSICAL PHILOSOPHY

Introduction

  • The term philosophia/philosophos: referred to “love of wisdom”
    • cf. sophos and sophistes
      • the former, wisdom
      • the latter, a wise person. Where we get sophists from, in English
  • In the 300s BC, we have Platos and Aristotle, etc
    • The term phisolophy took on a life of its own, and there was lots of contention regarding it
      • phisolophy became a word that everyone wanted to claim, because it represented everything good about wisdom and knowledge
        • like democracy, today. Everybody wants to claim they’re democratic, but it seems like many different people have different ideas of democracy
A) Socrates
  1. Who was Socrates?
    • physikos, sophist, or something new?
      • cf. The Clouds
  2. Practices
    • Socratic Irony
      • The Apology
        • the wisest person is the one who knows that he knows nothing
        • Everywhere Socrates went, he’d ask “why do you think …”
          • people would give an answer, and Socrates would subvert everything they said
          • when people asked Socrates what he thought things were, he’d say he doesn’t know
    • Dialectic
      • ask questions (especially of experts), challenge assumptions, seek a universal definition
      • always a dialogue to try to figure out what was true
B) Other “Philosophers”

People didn’t recognize these people as philosophers

  1. Xenophon
    • wrote socratic dialogue
    • was too practical, and mostly talked about ethical things, rather than profound metaphisms like Plato did
    • would have said he was a philosopher
      • cf. Apology
  2. Isocrates
    • humans as logical/rational beings
C) Plato
  1. Dialectic not Rhetoric, episteme (knowledge) not doxai
    • Plato would just have dialogue over and over, and doesn’t really present much episteme
      • Plato said you needed episteme in order to find truth, but never really got it…
    • doxai are opinions, and Isocrates was based on doxai
  2. Idealism
    • The changing world is the world we live in
      • “What is a chair?”
        • Different chairs share some kind of “higher connection” of chairness
          • in the ideal world, we find this connection. It participates in the unchanging nature of the idea world.
          • Chairness doesn’t change
    • cf. Parmenides
    • Plato never came to settle with ideas. He focused on the dialectic nature of coming up with ideas
  3. Influence
    • “The safest general characterization of the philosophical tradition is that is consists of a series of footnotes to Plato.”
      • Alfred North Whitehead
D) Aristotle
  1. Approach
    • ditched Plato’s idealism
    • the ultimate good is not just transcendent but also immanent
    • collects and examines specimens
      • and draws conclusions from numerous separate cases
      • rather than saying there’s an idea of fishness unchanging, Aristotle looked at specimens in the natural world
        • biological, constitutional, books, etc

CLAS201, 2017-06-21

THE RISE OF MACEDONIA

I. EARLY HISTORY OF MACEDONIA

A) Amyntas I (512 BC)
  • Ally/vassal of Persia
B) Alexander I (498-454 BC)
  • As well as the other 5th century kings
  • The Hellenizing of Macedonia
    • NB. Euripides died in Macedon
      • Got sick of Athens, and was invited to Macedon by the King to write and put on plays
  • Sometimes, during the Peloponnesian War, Macedonians were allies with Athens, sometimes not
C) Early Fourth Century (300s)
  • Post-Peloponnesian War
  • Much instability
    • 8 Kings from 400-359 BC
    • Was being pressed by the tribes around them, as well as the Greeks on the coast
    • A lot of Macedonians were not monogamists
      • Kings liked to have lots of wives, which resulted in lots of kids
      • In the early 300s, had lots of infighting in the Macedonian royal family
        • too many cousins and brothers vying for the throne

II. MACEDONIANS: GREEKS OR BARBARIANS?

A) Language is a little ambiguous
  • Surviving inscriptions suggest that Macedonians spoke a language that was closely related to that of the Northwest Greeks
    • Lots of dialects, like Ionian, Dorian, etc…
  • Some stories suggest that when Greeks tried to talk to the Macedonians, they couldn’t understand them.
B) Culture
  • Government(s) of Macedonia was not like the city states of the Greeks
  • Like a feudal system
    • Kings ruled, with some loyal nobles
      • Homeric leadership
        • Multiple kings; a high king, and some lower kings. The lower kings wouldn’t always be loyal to the high king
        • Macedonians looked Greek in their government only in their primitive Homeric style
          • 1 king, and other lesser kings subservant to the high king
    • the Monarchy was the state
      • the kingdom/country is embodied in the King
        • unlike the Greek city states, which had a highly developed sense of citizenship
    • cf. Greeks had a very different, republican government
      • Macedonians looked down on them for not having a good gov’t
  • Cultural practices
    • polygamy (not monogamy)
      • cf. Philip’s marriages
      • Tumulus burials
C) Opinions of Other Greeks
  • Alexander I applied for the Olympic games
    • But Greeks looked at him and said he was not Greek.
    • Greeks were convinced, because the royal family of Macedonia descended from the royal family of Argos
  • Herodotus
    • Doric Greeks
  • Isocrates
    • Greeks, Macedonians & barbarians
  • Demosthenes
    • Barbarians
D) Modern Controversy

IV. PHILIP II (359-336 BC)

A) Accession and Survival
  1. Hostage in Thebes (369-367 BC)
    • sent home when brother Alexander II was murdered
  2. Became regent/king in 359BC after disastrous battle against the Illyrians (and death of brother Perdiccas III)
  3. Made peace with Athens and Thrace, attacked Paeonians and Illyrians, made alliance with Epirus (Olympias)
    • There were a number of pretenders/cousins in Thrace, and the state was considering supporting one of them
      • However, Philip II convinced them not to, and to support him instead
B) Reforms and Innovations
  1. Military
    • Developed new siege techniques with torsion catapults and elite corps of engineers
      • Philip II was very aggressive, and wanted to take over resistant cities
    • Macedonian phalanx
  2. Administrative
    • Royal Pages
      • consolidated his hold over the nobility
      • a way of training/educating young people to be administrators and leaders in his government
        • somewhat sinister, because these Pages were like hostages
        • Philip II controlled these noblemen, whose sons were the Pages
          • Should these noblemen rebel, their sons would probably not be safe
    • Expanded the hetairoi and added the pezetairoi
      • hetairos means companion in Greek
      • Philip II wanted to mobilize the common people more effectively in his army (using the Macedonian Phalanx)
        • the pezetairoi let these common people gain a little favour with the king, allowing Philip II to build a more expansive army
        • this centralized Philip’s power
C) Expansion
  1. Constant expansion by astute diplomacy and successful military ventures
    • eventually conquered all of Greece in 338 BC
      • Epirus
        • Macedonia didn’t necessarily conquer Epirus, but they formed a strong alliance
          • they had similar cultures, etc
      • Thessaly
  2. Battle of Chaeronea (338 BC)
    • Macedonia v. Thebes & Athens
      • two rather powerful Greek states, but Philip II beat them pretty badly
        • treated Thebans harshly and severely.
          • Demanded all the people who had opposed him to be executed or exiled.
          • Families of hostages from Thebans were given a high ransom
        • treated Athens much more leniently
          • Marched the fallen soldiers of Athens back to their state
          • Gave their hostages back
          • May have been due to a high level of respect for Athens as a center of culture
            • Or maybe political, because Athens had a significant navy, which Philip II needed
            • Philip wanted to conquer Persia, and he needed a navy to do so
    • League of Corinth (Hellenic League)
      • for peace in Greece and war against Persia
        • NB. the 4th c. appeal of a pan-Hellenic expedition against Persia
          • This new Hellenic League was like the old one, with a similar purpose: to fight against Persia
          • This naming allowed Greeks to rally behind it, given their old animosity towards Persia
      • Sparta was not included. They were rather secluded in nature, and their power had severely decreased by this point
      • Historians now call it the League of Corinth, as it was formed in Corinth.
        • And reduces confusion (there are 2 Hellenic Leagues)
          • Philip called it the same thing for political reasons
      • If the Greeks wanted to get out of their 4th c. funk, they needed to unite
        • Isocrates wrote about practical issues, like how the Greeks needed to (unite and) defeat Persia
          • too many Greek young men doing nothing, hired as mercenaries by various Greek states and Persia itself
          • war against Persia could solve the in-fighting between states, if all states united against Persia
D) Death of Philip II
  • By 363 BC, Philip II died (quite quickly after the Battle of Chaeronea)
    • by this point, he controlled practically everything
      • except Sparta
      • except a few independent Greek states near Byzantium
  • Two accounts of his death
    • one personal
      • Philip was holding a public ceremony in one of his capitals. One of his bodyguards assassinated him
      • Pausanias (former lover) and Attalus
        • Philip didn’t want to piss off Attalus, one of his powerful nobles, didn’t punish him.
        • He tells Pausanias to become one of his bodyguards
          • Probably a bad move, since Pausanias was still pissed off
    • one political
      • Philip had married quite a number of times. A few Thessalians, a Scythian, etc
        • These were all political marriages
        • To build power in Thessaly, he married a few Thessalian noblewomen
      • The last marriage was for love, and this was considered a mistake
        • Fell in love with a young Cleopatra, the neice of Attalus
        • Alexander the Great had been designated the heir of Macedonia, however, this marriage to Cleopatra put Olympias and Alexander’s position in danger
          • the latter fled Macedonia, and plotted the murder of Philip II, to prevent an heir through Cleopatra
        • This story doesn’t exclude the personal aspect of the assassination

CLAS201, 2017-06-21

ALEXANDER THE GREAT

I. BIRTH & ANCESTRY

A) Birth (356 BC)
  • Mother: Olympias, Molossian princess
    • Married Philip II to cement the Thessalian alliance
    • By all accounts, a formidable woman
    • After the death of Alexander the Great, became very powerful politically. Often wrote letters to Alexander regarding states not doing what she wanted.
      • Women seemed to have a higher position in the Hellenistic era than previous eras
      • A harbinger of …
  • Siblings: full sister, Cleopatra (younger sister), half-brother, Arrhidaeus (older, but unsuitable for kingship)
  • clear heir to the throne
B) Ancestry
  • Descendent from Heracles on his father’s side, and Achilles on his mother’s side
    • cf. son of Ammon
      • son of Zeus. However, this would make him an equal of Heracles
      • Olympias seems to have something to do with this
        • apparently, said that when she became pregnant, she found a snake in her bed, a symbol of divinity
        • this gave Alexander a problem, since
    • cf. Iliad and tomb sacrifice
    • Philip’s family was considered descendents of the royal family of Argos
      • Traditionally, the Greeks said this royal family was descendent from Heracles, so this claim made sense historically
      • Became a very aggressive military leader
      • Kept the Iliad with him
        • Kept a dagger under his pillow, along with a copy of the Iliad

II. EARLY LIFE

A) Education
  • Greek tutors, including Aristotle
    • cf. Callisthenes
      • a nephew of Aristotle, also well-educated and known to be a literary scholar
      • brought by Aristotle to be the court historian, to write the story of Aristotle in the most effective way possible
  • Sources of Alexander’s life
    • lots of people/eye-witnesses wrote the events of his life
    • many of his generals
    • lots of phyiscal accounts, but few of these accounts survived
      • historians tried to piece his life together
    • had some secondary sources
    • how do we tell which account is correct?
  • Prodigy:
    • tamed Bucephalus, the untamable horse at 12 yrs old
    • regent (16)
    • cavalry commander at Chaeronea (18)

III. ACCESSION TO THE THRONE

A) Challenges
  • Cleopatra and family
    • Olympias and Alexander eliminated Cleopatra and her daughter. Philip II and Cleopatra’s marriage was a threat to Alexander’s position
  • Amyntas IV, original heir to Perdiccas III
    • Philip II came to the throne, initially, as a regent to Amyntas IV
    • Eventually, Philip II chose to seek the throne instead of remaining a regent
  • Regardless, Alexander’s kingship probably wasn’t in danger
    • He was a regent, and such a successful military hero
B) Consolidation
  • Philip II was highly successful. So, when Alexander came to the throne at a very young age of 20, there was some doubt
  • Greece
    • affirmed as a hegemon of the Corinthian League
  • Thebes
    • still didn’t like how Macedonia was doing things
    • talked some shit about Alexander (reporting/over-exaggerating his supposed death)
      • Alexander marched over and wooped them before they could ally with other states against Macedonia
    • Alexander razed all their buildings except the temples and Pindar’s house

IV. CONQUEST OF ASIA

A) Invasion
  • Combined real aggression and confidence, and blasted Asia
  • Granicus River (334 BC)
    • first major battle
  • Issus (333 BC)
    • control of royal family & treasury

C) King of Asia
  1. Battle of Gaugamela (331 BC)
    • Darius was ready to give Alexander (bribe him) in order to achieve peace. Alexander was offered half the Persian kingdom, but the fucker wanted it all.
    • Alexander finally smashes Darius and gains access to the heartland of the Persian Empire.
      • Didn’t capture or kill Darius, who ran away
  2. Babylon, Susa, Persepolis
    • Alexander allowed Satraps to keep their administrator positions
    • Goes to Marduk and accustoms himself to local customs
      • So that the Persians can see him as one of “them”, rather than a barbaric invader
    • At Susa, the gates were open to him, and he treated people quite nicely, and followed local customs
    • At Persepolis, his mood changes, and famously burned the city to the ground
      • not because Persepolis resisted him
      • Persepolis was the traditional capital of the Persians themselves
        • the Babylonians were in the Persian Empire, but they weren’t persians
        • Neither was Susa, really
      • Alexander appeals to his Greco-Macedonian/Greek followers and destroys the Persians
        • Shows that he is very politically astute
  3. Death of Darius (330 BC)
    • Alexander presents himself as a protector of the Persian royal family.
    • Darius III was killed by the Satrap Bessus
  4. Going Native
    • dress, proskynesis, Roxane
      • very clear political goal: to win over the Persians
    • Roxanna and Alexaner bear a child, which didn’t sit well with the Macedonians
      • This probably didn’t sit well with them, and may have led to a resistance
    • Macedonian Resistance
      • Clatus, who saved Alexander in a previous battle, was skewered by Alexander by a spear for complaining about his Persian assimilation
      • A number of the Pages began rebellion, trying to kill Alexander. These Pages were discovered
        • and Calisthenes was killed as well
      • Things were not going well between Alexander and the Macedonian rebellions
        • These never really bothered or threatened his power
D) India

India at the time refered to the area of Pakistan. The broader idea of India

  • Afghanistan and Pakistan
  • Indus River, etc.
  1. Initial victories
    • Hydaspes (326 BC)
      • offered lots of issues for Alexander in the beginning of this conquest.
      • Allied with King Taxiles to defeat King Hydaspes
      • Instead of attacking across the flooded Hydaspes River, Alexander went around, further upstream, crossed the river, and came crashing down on Porus (the King of Hydaspes) and his elephant army from the north (during the night)
        • Won a great victory
        • But so impressed with Porus (his air of nobility) that he offers him continued kingship, against the behest of Taxiles
  2. Refusal of soldiers
    • When Alexander realized there was still a lot of Indian land to claim, he was not daunted
  3. Return home (325 BC)
    • One of Alexander’s commanders took a bunch of money and returned to Greece.
    • Eventually, Alexander got back and settled
    • Still, went back to try to merge the Persian elite and Macedonian elite into one fused elite.
      • Married some daughter(s) of past kings of Persia
      • Ordered nine of so of his commanders to marry into Persian nobility
      • Married thousands of people to Persian citizens
    • By all accounts, doesn’t look like Alexander’s followers (esp. his generals) thought this was a good idea
    • Alexander died in 323 BC, and when he did, almost every one of his commanders left their Persian wives.
  4. Death, in Babylon (323 BC)
    • Some say he was poisoned
    • Most historians believe he died of some kind of infection or disease
      • he languished for a couple of weeks with a high fever, and eventually succumbed
      • it’s thought his body was weak due to his years of conquest, causing him to be susceptible to disease
E) Final Actions and Plans
  • Asian marriages
  • Persian “successor” infantry
    • Up to this point, the Macedonians acted as the crack infantry troops
      • hetairoi, foot companions close to the king
      • Alexander replaces the pezatairoi with his new Persian troops
        • to be fair, his old phalanxes were getting old
        • he sent 10,000 back to Macedonian to retire
          • lots of tension amongst the common soldiers about the new Persian troops, so this helped quell that situation
    • Called these new Persian infantry, the “successors”
      • kind of weird
  • Future conquests (Arabia and Carthage)
    • Looked like he was planning to conquer Arabia, but he died and wasn’t able to fulfill these plans
    • In some ancient accounts, he was planning to conquer Carthage as well
      • basically the entire Mediterranean
        • some contention over this

V. EVALUATION

He is called “the Great,” after all

A) Opinions on Alexander
  • early 20th century, people thought Alexander as a great conqueror
    • this is the hayday of western conquerors
      • Britain and other European empires would think Alexander was great
    • we can look at him as just a politician who conquered and colonized and did what he could to stay in power…
  • Proponent of Hellenism?
    • Alexander liked literature and Greek culture in every way
    • He brought the superior culture of the west to the east
    • Planted many of Greek cities (recall the near 70 Alexandrias)
  • Uniter of humanity?
    • eg. Alexander was not xenophobia
    • Conquered Persia, but elected to assimilate them into the Macedonian Empire
      • even though the Macedonians didn’t appreciate that
      • granted, it could have been a purely political decision (to win favour), but we can potentially read him as a uniter
  • Brutal conqueror?
    • nowadays, attitudes toward conquest and colonialism have changed dramatically, so we can certainly view him as brutal, but the times were different back then
    • Of course, opinions on Alexander change as societal culture changes.

VI. SUCCESSORS

After the death of Alexander, his offspring did not succeed him. He had a young son (Alexander IV), but he was used as a political pawn by Macedonian generals

  • He was killed when he was 13 or 14
  • The heir of Alexander was good propaganda value
    • the generals didn’t want him on the throne (people would think 13 or 14 is a ripe time to take the throne)
  • Alexander had some half-brothers who was also killed
    • Macedonian generals took over

The Ptolmeic Kingdom

  • Ptolemy settled down in Egypt and took over, beginning the Ptolmeic Kingdom. The last of the Ptolemies was Cleopatra VII.
  • The Ptolemies tended to ally themselves with the Romans. The king

The Seleucid Kingdom

  • Again, one of the commanders of Alexander
  • Wasn’t as quick as Ptolemy, but also managed to rule some land north of Egypt

The Antigonid Empire

The Roman Empire

  • One of the first Greek states to fall was the Macedons
  • The Romans hated kings, which played a small role in their destruction of the Greeks
    • Conquered the Seleucids
    • Conquered the Ptolmeics after Cleopatra played the wrong cards

CLAS201, 2017-06-28

HELLENISTIC SOCIETY

I. POLITICS

A) Poleis (City-states)
  1. Democracy
    • Athens
      • 322 BC, democracy dismantled
        • survived in a limited form at Athens
        • The Lamian War
          • tried to drive out the Macedonians garrisoned in Athens, but the regent of Macedonian (who Alexander put in charge) came in and smacked Athens
            • this was right after Alexander died
            • The Macedonians dismantled the democracy of Athens and ran the city
      • the poleis went down the crapper. The Greek city states were fighting for position but they didn’t survive in their old glory form
        • this might be an over-simplification
          • many Greek city states still maintained partial independence, and flourished
          • most couldn’t determine foreign policies (because the king ruling over them would determine that)
          • but the king didn’t really care about what the states did amongst themselves
      • Demetrius of Phalerum (317-307 BC)
      • When the Romans came, Athens heeded them, and the Romans sort of let them be.
        • so, Athens sort of survived as a democracy, but had to negotiate their kingdom
    • Elsewhere
      • Alexander favoured democracies
        • eg. Ionian cities
          • Alexander took over all the old Ionian coast city states. He set up democracy here
          • During the Hellenistic, there seemed to be an admiration for the Ancients of Greece
            • so, they considered Classical Athens democracy
        • The Persians mostly liked to set up tyrants (they sometimes set up democracy)
      • Athens was an anomaly
  2. Expansion of City-States
    • The Hellenistic Era could be seen as a golden age of the poleis
    • Alexander and Successors established many poleis across the east (Alexandrias)
      • this appears to be an expansion of Greek cities
      • these Greek cities were not fully independent, but neither were the city states of Ancient Greece
B) Federal States
  1. Federations of cities (not necessarily ethnically based) with local and federal political structures
    • eg. modern provinces and a federal government umbrella
    • eg. Boeotian League
      • sometimes, depending on the politics of Boeotia, the cities of Boeotia were fighting each otehr
        • Mostly independent city states in Boeotia
        • but Thebes would come to dominate
    • Hellenistic Era
      • Aetolian League (370-189 BC)
        • this League had already formed from Classical times, but became important in Hellenistic Era
          • around 320BC, the Romans set their eyes on the Macedonians, who had allied with Hannibal (who ravaged the Italian countrysides)
            • After the Romans finished off Hannibal, they came to end the Macedonians
            • The Romans allied with the Aetolian League, as long as the Aetolians were friendly
            • After the Aetolians finished off the Macedonians with Romans, they wanted to do their own business, but the Romans wanted them to follow their orders instead. Bad things happened to the Aetolians.
        • Just Aetolian cities (same dialect, religious cites, etc.)
      • Achaean League (280-146 BC)
        • Reached out to various other cities in Northern Peloponnesus
        • First allied with Romans against the Seleucid Kingdoms
        • Romans beat them up after the Achaeans didn’t do what the Romans said
        • Kept fighting with Sparta

II. SOCIETY

A) Greeks
  • Many opportunities for scholars, artists, and soldiers opened up in new kingdoms
    • Recall Isocrates said the Greeks needed to unite and fight against Persia, so that citizens would have something to do
      • this “problem” was solved in the Hellenistic Era by the appearance of these new Kingdoms
      • These Kings had lots of money, and liked to win prestige by winning battle
        • So, was always looking for good soldiers
        • Also focused on building large libraries and showing cultural sophistication
B) Non-Greeks
  • Like native Persians, Babylonians, etc.
    • Some opportunities with assimilation into dominant culture were given
      • eg. Jews in Egypt
        • Lots of people in Alexandria were native Egyptians.
        • Certain ethnic groups were given more privileges than others
        • The Jewish needed to translate their old Hebrew scriptures (which they could read anymore) into Greek languages.
          • they kept their distinctive cultural practices, but assimilated into Greek society linguistically
          • In lots of ways, they also adopted Greek philosophies
        • Extension: Philo attributed the Jewish people’s Monotheism with Platonism. This is another example of cultural assimilation
C) Women: Greater Opportunities
  1. Royal women and eurgetisms
    • Women had higher positions in Hellenistic society, as compared to Classical
      • This is thought to be due to the power of the Royal women
      • esp. the Ptolemies
        • adopted some traditional Egyptian ideas, and raised the status of their royal family to the status of deity
        • they tended to inter-marry
          • if you are so much higher in status as royalty, who’re you going to marry?
      • This exaltation, by nature, made the women much more prominent place in society
      • Ptolemy the first, and his wife, were placed side by side on a coin. They were, together, seen as divine.
    • Had inscriptions honouring the eurgetism of women
      • Eurgetism referred to being a benefactor (good-deed-doer)
        • Greek women were elected as magistrates because they gave money to their local Greek city
          • built a great public building at their expense for the sake of the city, etc.
          • this idea of eurgetism went further, and extended to rich people, and even kings
  2. Education
    • eg. Hipparchia
      • Wife of a cynic philosopher named Crates
      • Was also a philosopher
        • didn’t really occur in Classical Greece. Some female poets, maybe, but not philosophers

CS 343

Introduction

0.1 Why concurrency

  • Processor speed has slowed (stopped)
  • Use transistors from Moore’s law for parallelism to increase speed
    • Every 18 months, double number of transistors
  • But concurrent programming is still necessary to utilize parallel hardware
    • Very few devices run on single cores
  • Some success in implicitly discovering concurrency in sequential programs
    • For a certain class of problems, can convert existing sequential programs into concurrent programs
  • Alternately, programmer explicitly thinks about and specifies concurrency
    • Implicit and explicit approaches are complementary
    • Limitations of the implicit approach mandate the explicit approach

0.2 Why C++

  • C++ is a dominant programming language
    • Based on C (large programmer- and code-base)
    • as efficient as C in most situations
    • Low-level features, eg. direct memory access, needed for
      • Systems programming
      • Memory management
      • Embedded / real-time
    • High-level features, eg. exception handling, objects, polymorphism, STL, etc.
    • Allows direct interaction with UNIX/Windows

0.3 Concurrency in C++

  • C++ originally had no concurrency
    • C++11 only has simple concurrency
  • Many different concurrency approahces for C++ have been introduced, with only varying degrees of adoption
  • No de factor approach that dominates C++ concurrency programming
    • C has two but incompatible, pthreads and Win32
  • C++’s simple concurrency limits its future in parallel computing
  • Cannot be safely added to ANY language view library code

0.4 High-Level Concurrnecy

  • In theory, and high-level concurrency approach can be used and adapted to C++. Some are better than others
    • C++ is class-based. Need to find a model that matches the models/architecture of your language
  • We want a single consistent high-level powerful concurrency mechanism, but what should it look like?

0.5 mC++

Advanced control flow C++

  • Integrated advanced control flow tightly packed into C++
    • Leverage class features
    • Threads are light-weight: M:N thread model versus 1:1
  • Use mutex objects to contain mutual exclusion and synchronization

0.6 Outline

1 Advanced Control Flow (Review)

Basic and advanced control structures allow virtually any control flow

  • Still, need more than ifs and whiles
    • eg. do-while, always at least once
      • whiles check at the top, and run through.
      • do-whiles run through, and checks at the bottom
      • What about the middle?

Multi-exit loop

for (;;) {
	// { priming }
	if (...) break;
}
  • Can add loop index and take it out freely (as opposed to swap between whiles and fors)

1.1 Static multi-level exit

  • Exit multiple control structures wher exit points are known at compile time
  • Labelled exit (break/continue) provides this capability
mC++ / Java

L1: {
	// decs
	L2: switch (...) {
		L3: for (...) {
			...
			break L1; // exit block
			...
			break L2; // exit switch
			...
			break L3; // exit loop
		}
	}
}

1.2 Dynamic Memory Allocation

To avoid mark deductions, do not perform dynamic allocation unless necessary

  • Dynamic allocation is bad for concurrent programming
  • Sometimes, it’s equally bad for sequential programming
  • Stacks are more efficient for various reasons than heap allocation
    • Also, does not require explicit storage-management when working with stack

Fundamentally, when a variable’s storage must outlive the block in which it’s allocated, then it must be allocated on the heap

  • Exceptions
    • Unknown amount of data (eg. reading from a stream)
      • Vectors heavily utilize the heap (in order to grow larger, needs to allocate heap space)
      • So, be careful of the structures you’re using

2 Dynamic Multi-level Exit

  • Routine activation (call/invocation) introduces complex control flow.
  • Among routines, control flow is controlled by call/return mechanism.
    • Routine h calls g calls f
    • Cannot return from f to h, terminating g
  • Modularization
    • Any contiguous code block can be factored into a (helper) routine and called from anywhere in the program (modulo scoping rules)
  • Modularization fails when factoring exits, eg. multi-level exits
    • Labels only have routine scope
      • Be wary when moving labels and code (with variables) into a separate routine
      • This is a downstream consequence when switching a style of control flow

How would/could we fix this problem?

  • Fundamentally, routines can have multiple outcomes
    • routine call returns normally, ie. statement after the call
    • exceptional returns, ie. control transfers to statements not after the call
      • eg. could not compute width or height, throw exception

[Notes 6]

  • Fortran example
  • Generalization of multi-exit loops and multi-level exits
  • This Pattern addresses a few things
    • Algorithms can have multiple outcomes
    • Separating outcomes makes it easy to read and maintain a program
  • Pattern does not handle case of multiple levels of nested modularization

[Notes 7]

  • Dynamic mutli-level exit extend call/return semantics to transfer in the reverse direction to normal routine calls, called a non-local transfer
  • We can keep references of labels, and these are determined during run-time, hence dynamic exits

Non-local transfers

  • Mechanism behind this is a label variable containing the tuple
    • Pointer to a block activation on the stack
    • Transfer point within the block
  • goto L, in f, is a two-step operation
    • Direct control flow to the specified activation on the stack
    • Then go to the transfer point (label) within the routine
  • Therefore, a label value is not statically/lexically determined
    • Recursion in g ==> unknown distance from f and h on stack
    • What if L is set during the recursion of h?
  • Transfer between goto and label value causes termination of stack block

2.1 Traditional Approaches

  • Return code
    • returns value indicating normal or exceptional execution
    • eg. printf() returns number of bytes transmitted, or a neg. val
  • Status flag
    • Set shared (global) var indicating normal or exceptional execution
    • the val remains as long as it is not overwritten
    • eg. errno var in UNIX
      • Anytime a library routine is called, it will have a return code, put into errno
  • Fix-up routines
    • a global and/or local routine called for an exceptional event to fix-up and return a corrective result so a computation can continue
    • eg. C++ has a global routine-pointer new_handler called when new fails
  • Techniques are often combined
    • eg. we should probably check if printf() returns a neg. val, which indicates an error
    • We don’t explicitly do this… ever
      • However, errno will be populated with 27
      • `perror(“printf:”);
        • Looks up errno==27 in its table and prints a message accordingly
    • Finally, can abort() if printf() fails
    • This means every library routine call should introduce a minimum of 3 additional lines
      • Who the fuck does this?
  • Intermediate approach of return union, which mimics normal return type
  • Return union combines result and return code, and checks code on result access
  • ALL routines must return an appropriate union

[Notes 9]

  • malloc, for instance, returns a storage, or a “no” message
    • ie. a union of the right and wrong outcome
    • Rust automatically dereferences and checks if malloc fails
      • Forces the check to be done, even if not explicitly performed
    • In Rust, it is literally a union: a struct that contains multiple values
      • eg. Result<void *, NoStorage>

Drawbacks

  • Checking return code or status flag is optional
    • can be delayed or omitted, ie. passive vs. active
  • Return code mixes exceptional and normal values
    • enlarges type or value range; normal/exceptional type/values should be independent
    • What if we can print negative characters? Then how can we find a value that could also be a return code?
    • If a routine uses all the positives and negatives, how can we steal one of those values to indicate an alternative result?
  • Under no circumstance should a library routine abort the program
    • Should pass errors up so that someone else can make the decision as to what to do
    • The error should be passed up multiple levels (eg. A -> C, then back to A?)
  • errno could have been changed many times since the error occurred *…
  • Local fix-up routines increase the number of parameters
    • Increase cost of each call
    • Must be passed through multiple levels, enlarging parameter lists even when the fix-up routine is not used

2.2 Exception Handling (Model)

  • Dynamic multi-level exit allows complex forms of transfers among routines
    • Exceptions aren’t “errors”
    • They’re a good way of moving away
    • Exceptions are alternate outcomes, though usually ancillary
    • Exceptional event is an event that is (usually) known to exist
      • Usually occurs with low frequency
      • eg. Division by zero, I/O failures, EOF
  • Very difficult to simulate EHM using simpler control structures
  • Exceptions are supposed to make certain programming tasks easier, like robust programs
  • Robustness results because exceptions are active vs. passive; forcing programs to react immediately when an exceptional event occurs
  • An EHM is not a panacea, and is only as good as the programmer using it

2.3 Execution Environment

  • An OOP concurrent environment requires a more complex EHM than a non-object-oriented sequential environment
  • Sometimes, need to walk through the stack frame and execute all destructores
    • Finally clauses are always executed
      • _Finally in mC++

2.4 Terminology

2.5 Static/Dynamic Call/Return

  • Static: can deduce exactly what will happen
  • Dynamic: when code is being executed, things and executions may change
    • Calls may return statically or dynamically

2.6 Static Propogation (Sequel)

  • Case 1) static call, static return
  • Sequel
    • Routine with no return value
      • Sequel name is looked up lexically at the call site
      • Though, control returns to the end of the block in which the sequel is declared
        • Doesn’t go back to executing call, so no return values
    • Can change breaks into sequels
  • Without sequels, it’s impossible to modularize with static exits
    • Thus, propagation is along the lexical structure
  • Adheres to the termination model, as the stack is unwound
  • Sequel handles termination for a non-recoverable event (simple execution handling)
{
	sequel StackOverflow(...) {...} // handler
	class stack {
		void push(int i) {
			if (...) StackOverFlow(...); // 2nd outcome
		} // 1st outcome
		...
	}

	stack s;
	...
	s.push(3); // overflow?
}
  • The second outcome is basically a simple exception. When it occurs, execution jumps outside of the sequel block
    • Problem, doesn’t work for separate compilation
      • Want to pull stack out into stack.cc?
        • What happens to StackOverflow? Where is the sequel?
        • The sequel has to be seen statically to know where it must jump to after execution
      • This is the same issue with routines’ scope issue
    • Only works for monolithic programs
    • Fails for modular (library) code as the static context of the module and user code are disjoint
  • Advantage of the sequel is the handler is statically known (like static multi-level exit), and can be as efficient as a direct transfer

2.7 Dynamic Propagation

Case 3) dynamic call, static return

  • Termination
  • Also called dynamic multi-level exit
  • Advantage
    • Dynamic propagation works for separately-compiled programs
  • Disadvantage
    • Handler is not statically known
    • Without dynamic handler selection, the same action and context for that action is executed for every exceptional change in control flow
2.7.1 Termination
  • Control transfers from the start of propagation to a handler –> dynamic raise (call)
  • When handler returns, it performs a static return –> stack is unwound (like sequel)
  • There are 3 basic termination forms for non-recoverable operation
    • non-local, terminate, retry
      • non-local transfer provides general machanism for block transfer on call stack, but has goto problem

Terminate provides limited mechanism for block transfer on the call stack (like labelled break)

  • Catches are similar to sequel. They both have static returns, and jump to the end of the block (next line after block)

Retry is a combination of termination with special handler semantics

  • ie. restart the guarded block handling the exception
  • Pretend EOF is an exception of type Eof
    • Not supposed to get out of retry until contract is fulfilled
    • Can have alternative ideas than catch clauses
  • With just a normal catch clause and a few extra lines, can simulate retries very easily
    • Don’t need an extra construct, so C++, Java, etc. don’t have it
Case 4) dynamic call, dynamic return

Resumption

  • provides a limited mechanism to generate new blocks on the call stack
  • control transfers from the start of propagation to a handler –> dynamic raise (call)
  • when handler returns, it is a dynamic return –> stack is not unwound (like routines)
  • Using _CatchResume clauses and _Resume raises, when the closing brace is reached in the _CatchResume, execution is returned to the _Resume call, not the next line after the handler
    • O(n) search, which we don’t get from an O(1) return call
    • Normally, we’d have to pass a fixups around

2.9 Exceptional Control-Flow

Shits bonkers, yo

3.0 Coroutines

A coroutine is a routine that can also be suspended at some point and resumed from that point when control returns

  • A calls B, B calls C, C goes back to B
    • That sounds like routine calls to me
      • Yes! But, C doesn’t terminate… (?)
  • The state of a coroutine consists of
    • An execution location, starting at the beginning of the coroutine and remembered at each suspend
    • An execution state, holding the data created by the code the coroutine is executing
      • Each coroutine has its own stack, containing its local vars and those of any routines it calls
    • An execution status, active, inactive, or terminated
      • Changes as control resumes and suspends in a coroutine
  • Not a normal routine because coroutine creates a new stack, and starts running there

  • Coroutines handle the class of problems that need to retain state between calls
    • eg. plugins, device drivers, finite-state machines
  • Coroutines exectue asyncly with other coroutines, hence no concurrency among coroutines
    • Coroutines are the precursor to concurrent tasks, and introduce the complex concept of suspending and resuming on separate stacks

When you create a routine, you don’t declare whether its recursive or sequential.

  • Semi-coroutines and full-coroutines are different types, non-declarative
    • Semi-coroutines act asymmetrically, like non-recursive routines, by implicitly reactivating the coroutine that previously activated it
    • Full-coroutines …

3.1 Semi-Coroutine

3.1.1 Fibonacci Sequence
  • Direct method is simple enough
  • Create a routine called fibonacci()
    • Problem, after every fibonacci call, we’d lose data regarding the already-computed values
    • We needed to introduce global fn1 and fn2 variables to retain state
    • Also, fibonacci has three different states
      • if n==0, n==1, or n>1
        • Which state? They return different things
  • Classes are fun, but still don’t get the job done too well
    • We can create a Fibonacci class, and encapsulate our global variables
    • Also, can now have multiple instances, so create fn1 and fn2
      • next() generates the next Fibonacci number for the given instance
    • Still has flag variables

Using coroutines

_Coroutine Fibonacci {
	int fn;
	void main() {
		int fn1, fn2; // retained between resumes
		fn=0;
		fn1=fn;
		suspend()
		fn=1;
		fn2=fn1;
		fn1=fn;
		suspend()

		for (;;) {
			fn = fn1+fn2;
			fn2=fn1;
			fn1=fn;
			suspend()
		}
	}

	public:
	int next() {
		resume(); // only resume (which increments our fib number) when necessarily
		return fn;
	}
}

int main() {
	Fibonacci f1, f2;
	for (int i=0; i<=10; i+= 1) {
		cout << f1.next() << " " << f2.next() << endl;
	}
}
  • No explicit execution state!
  • _Coroutine type wraps coroutine and provides all class properties
  • Distinguished member main (coroutine main) can be suspended and resumed
  • No parameters or return value (supplied by public members and communication vars)
  • main can be called (even recursively), but is normally private/protected
    • This is so that outsiders cannot fuck around with your coroutine
    • Outsiders can only interact with your coroutine in the ways you provide

Coroutines do context switches

  • On resume, will context-switch over to the coroutine stack
  • On suspend, will context-switch over to the main stack, or whoever called the coroutine
  • For example above, the frame for next() goes on the main stack
    • Doesn’t context switch until later. Sometimes, we don’t even need to resume/suspend, so it’s not a great idea to automatically context-switch
    • Even being on the main stack, it can still access variables from the coroutine(s) stack
    • Uses this variable to execute magic
  • By using separate stacks, coroutines get the power that they do
  • First resume starts main on new stack (cocall)
    • Subsequent resumes reactivate last suspend
    • suspend reactivates last resume
  • Object becomes a coroutine on first resume
    • Coroutine becomes an object when main ends
  • Routine frame at the top of the stack knows where to activate execution
    • suspend/resume are protected members to prevent external calls
      • So other people can’t diddle with your coroutine’s execution
      • Only protected when inheritance is needed
  • Coroutine main does not have to return before a coroutine object is deleted
  • When deleted, a coroutine’s stack is always unwound and any destructors executed
    • Why?
3.1.2 Format Output (Example)
  • Unstructured input: abcedfghijklmnopqrstuvwxyzabcedfghijklmnopqrstuvwxyz
  • Structed output
abcd efgh ijkl mnop qrst
uvwx yzab cdef ghij klmn
opqr stuv wxyz
  • Blocks of 4 letters, separated by 2 spaces, grouped into lines of 5 blocks
  • Traditionally, we’d use loops directly
    • [Notes 30]
    • If we try to modularize this code, we need to maintain variables for number of blocks and size of blocks
      • Need to remember how many characters are in current block
  • Coroutine trick
    • resume in the constructor
    • Normally, first time a public member is called, it will resume, which is the cocall and makes the stack
    • However, sometimes, we don’t want the user to make the first resume
      • This allows the programmer to make the cocall. This allows priming, putting the execution in the right position so that the first user resume makes sense
      • Sure, why not. I don’t ask questions
A1 Hint(s)

Don’t need to do money as a coroutine

  • Easiest way to write a coroutine is to pretend you’re a freshman
    • Just write the code straight up and get it working
    • Then change it into a coroutine
  • Much like formatter, our A1Q3 coroutine takes some input values and determines if the input is valid
3.1.3 Correct Coroutine Usage
  • Eliminate computation or flag variables retaining information about execution state
  • We had our good version of the Fibonacci coroutine
    • However, consider the example using a switch statement
      • In this case, an explicit flag var controls execution state
      • Original program structure is lost in the switch
3.1.4 Coroutine Construction
  • Fastest way to write a simple coroutine? Write it out directly, with some inputs and output, and take that code and put it in a coroutine, subject to change
    • Works well enough for simple coroutines
    • Put processing code into coroutine main
    • Converting reads if program is consuming or writes if program is producing to suspend
      • Fibonacci consumes nothing and produces Fibonacci numbers –> converts writes (cout) to suspends
      • Formatter consumes chars and only indirectly produces output (as side-effect) –> convert reads (cin) to suspends

4.0 mC++ Exception Handling Model

  • In A1Q3, need to throw an exception from one coroutine to another coroutine
  • mC++ exceptions are generated from a specific kind of type, which can be thrown and/or resumed
    • All exception types are grouped into a hierarchy
    • mC++ provides a set of predefined exception-types covering exceptional runtime and I/O events
  • mC++ restricts raising to a specific exception type
  • Supports two forms of raising, throwing, and resuming
  • Supports two kinds of handlers, termination, and resumption, which match with the kind of raise
  • Supports propagation of nonlocal and concurrent exceptions
    • Cross-stack exceptions

4.1 Exception Type

  • C++ allows any type to be used as an exception type. mC++ restricts exception types to those defined by _Event
_Event exception-type-name {
	...
};
  • An exception type has all the properties of a class
    • As well, every exception type must have a public default and copy constructor
  • An exception is the same as a class-object with respect to creation and destruction
_Event D { ... };
D d;
_Resume d;
D *dp = new D;
_Resume *dp;
delete dp;
_Throw D();
  • Note, C++ throw doesn’t have all the special features that _Throw does

4.2 Inherited Members

Each exception type inherits the following members from uBaseEvent

4.3 Raising

  • Can use _Throw, or maybe event throw, but the former provides additional funtionality

4.4 Handler

  • mC++ has two kinds of handlers, termination and resumption. They match with the kind of raise

Termination

  • The mC++ termination handler is the catch clause of a try block, same as C++

Resumption

  • A resumption handler is often a corrective action for a failing operation
  • Unlike normal routine calls, the call to a resumption handler is dynamically bound rather than statically bound
    • mC++ extends the try block to include resumption handlers
    • Resumption handler is enoted by a _CatchResume clause at the end of a try block
try {
	...
}
_CatchResume(E1 &) { ... }
// more _CatchResume clauses
_CatchResume(...) { ... }
catch(E2 &) { ... }
// more catch clauses
catch(...) { ... }
  • Any number of resumption handlers can be associated with a try block
  • All _CatchResume handlers much precede any catch handlers
    • The former is dynamic, the latter is catch
    • The former goes back to the raise, while the latter continues afterwards
  • Like catch(...), _CatchResume(...) must appear at the end of the list of the resumption handlers
  • Resumption handler cannot perform a break, continue, or return

Something about unwinding stack

4.5 Nonlocal Exceptions

  • Nonlocal exceptions are exceptions raised by a source execution at a faulting execution
  • Nonlocal exceptions are possible because each coroutine (execution) has its own stack
    • Nonlocal has to throw something at someone that has a stack

Problems with not using coroutines?

Device driver example
> Flow becomes linearized without coroutines. There is a very specific order of execution and it usually involves a method beginning and ending
> This can lead to inefficient code and over-complication, because we're forced to comply with the structure and flow of a regular method

CS349, 2017-05-01

INTRODUCTION

User interface: place where a person expresses intention to an artifact, and the artifact presents feedback to the person.

  • the term artifact can apply to any object, so things have hammers have “user interfaces” too…
Interactive System Architecture
  • [user] expresses –> [artifact] translates –> [artifact] presents –> [user] perceives
Model-View-Controller (MVC)
  1. [user] expresses intention
  2. [artifact] translates in the Controller, changes data in the Model, and notifies the View to update and present new visuals
  3. [user] perceives

Example

  • graphical temperature control
    • [user] expresses intention (e.g. mouse movements, mouse events)
    • [artifact] Controller translates mouse events
    • [artifact] changes Model data (sets max=30, temp=18, min=10)
    • [artifact] Model notifies View (draws widget with new data, and presents it to the user)
Interface vs. Interaction
  • Interface
    • external presentation to user
      • controls (what the user can manipulate/use to communicate an intent)
      • visual, physical, auditory (what program uses to communicate its response)
  • Interaction
    • used to connote behaviour: user must invoke to perform a task and the corresponding responses
      • interaction is action and dialog(ue)
      • unfolds over time

Why is interaction design difficult?

  • Variability in users and tasks
    • varying levels of expertise among users
    • often, a range of tasks will be performed using the same tool. How can we anticipate all the possible use cases and scenarios?
  • No single “right way” to design an interface: can always be improved
  • Pushing technology forward requires us to rethink interaction (innovate according to new expectations)

Why study interaction?

  • Well-designed interfaces empower users to do things they couldn’t otherwise do
    • movie production/editing, image editing, desktop publishing, …
  • Interaction is key to enabling new technologies
    • multi-touch and gestures
    • voice interfaces
    • touch screens for tablets/notebooks

This course will focus on the interaction and development of user-interfaces, not the user experience. User-centered design is covered in CS449

  • how to design, implement, and evaluate user interfaces
    • provide foundational knowledge for building highly interactive, usable desktop, web, and mobile applications
    • illustrate underlying architecture of modern GUI toolkits
    • explore strategies applicable across a range of interface problems
    • explore essential design tools, techniques, and processes
  • ways to understand users
    • the physical and cognitive abilities of users
    • visual design principles

See L1 Slides for info about assignments and the assignment assessment (skill tree)…

CS349, 2017-05-03

CS349, 2017-05-05

CS349, 2017-05-08

Design Principles

The goals of “good design”

  • What kind of devices do we want to make?
  • Useful vs. usable

Example: A remote control

  • Jakob Nielsen (UI Researcher) says he only uses 33% of the buttons on a remote control with regularity
  • The others only cause confusion and clutter
  • Obscure labels

As time goes by, devices (like remote controls) reach higher capabilities than humans

  • Usefulness: meeting specific needs & supporting real tasks; the quality of being practically useful
    • If there’s a high functionality (e.g. lots of items in a menu), usefulness may be high
  • Useability: the effectiveness, efficiency, and satisfation with which users can achieve tasks in a particular environment with a product
    • If the interface is poor and tasks aren’t easily done, then useability is low while usefulness may (or may not) be high.

In solutioning, we strive to achieve the optimal balance between the two.

Example: Refrigerator temperature control

Two controls: one for fridge and one for freezer. This implies that there are two systems/valves (or sources). However, these controls simply adjust the cold air flow coming from a single source, split into two.

  • This is somewhat un-useable, due to a lack of transparency

What can we learn?

  • Help form correct mental models (fridges, doors, phones)
  • Provide explicit controls for high-use functions
  • Appearances should reflect or suggest usage
    • e.g. push plates when doors are push to open, and pull handles when doors are pull to open
  • Low-use functions shouldn’t have the same level of suport as high-use functions
    • e.g. volume buttons on a remote are much more often used than the “setting” button
  • Give feedback of operations in progress
    • Helps improve transparency

Mental Models

Three models of a system

  • Developer’s model
    • How the programmer believe the system should be used
  • System model
    • The system itself
  • User’s (mental) model
    • How the user of a system believes the system should be used

The goal is to have these three images align as closely as possible. Mental models drive how users interact with a system

Model of Interaction

The basic idea is simple. To get something done, you have to start with some notion of what is wanted — the goal that is to be achieved. Then you have to do something to the world, that is, take action to move yourself or manipulate someone or something. Finally, you check to see that your goal was made.

Four things to consider

  • the goal
  • what is done in the world
  • the world itself
  • the check of the world

The action itself has two major aspects:

  • Doing something: Execution
    • What we want to do to the system
  • Checking something: Evaluation
    • Comparing: what happened vs. our goal

CS349, 2017-05-10

UI Design Principles, cont’d

Design principles serve to

  • reduce gulf of execution and gulf of evaluation
  • create and reinforce a more correct mental model for the user

Aspects of design principles

  1. Perceived affordances
  2. Mapping
    • Physical actions of input device mapped to a UI instrument
    • Instrument’s actions mapped to an object of interest
      • Degree of integration
        • ration of DOF of device to on-screen actions
      • Degree of compatibility
        • similarity in action and effect
    • Some things work well in the physical world, but not in virtual world
    • The relationship between two things: control movement and the effect it has in the world. Three types of mapping:
      • Layout
        • Burners on a stove and control dials should have the same arrangement
        • Radio buttons (single choice) should clearly map to a single section
      • Behaviour
        • Turning a car steering wheel in a certain direction should move the car in that direction
      • Meanings (conventions)
        • Emergency buttons are red
        • Up/clockwise means “more”
    • Components often mimic physical controls and follow the same conventions and mappings
  3. Consistency
    • Designing interfaces to have similar operations and use similar elements for achieving similar tasks
    • Follows rules, such as using the same name operation to select all objects
      • e.g. hovering over an object, and left-clicking to select
      • e.g. right-click to bring up a context-menu w/ actions
  4. Constraints
    • Guide by preventing certain actions while enabling/encouraging others
    • Example: Norman’s Lego Motorcycle
      • Physical: Lego blocks only fit one way
      • Semantic: Based on meaning. E.g. windshield protects driver, so it should go in front of the seat
      • Cultural: Red “means” brake
      • Logical: The last piece goes in the last remaining spot
    • Example: “Settings” on slide 48
      • Physical: You can only slide the slider so far left or right, bounded by 0% and 100%
      • Semantic: Folder icons indicate that files can be placed inside
      • Cultural: The dropdown icon indicates the color selection can be expanded
      • Logical: Naming of folders map to specific organization(s)
    • There isn’t a single set of cultural constraints. Certain places expect a RTL display. It’s important to understand the audience when dealing with cultural constraints.
  5. Visibility
  6. Feedback
    • Can happen at different levels
      • Widgets (like a button): do they articulate
        • that they are enabled or disabled?
        • that they have focus?
        • its current stateÉ
    • Does feedback communicate affordances?
    • When the user acts, does something happen on screen?
    • Is the user able to perceive new state of system model once the action is complete?
    • Examples of poor feedback:
      • Creating symbolic links in Linux
      • Online video buffering
    • Examples of good feedback:
      • Search and replace in Sublime Text
  7. Metaphor
    • Set of unifying concepts in a GUI used to simplify interaction
    • Done by borrowing concepts from one domain (the source, or vehicle) and applying them to another (the target, or tenor)
    • Scale can vary from system, to application, to UI feature
    • Examples
      • Desktop metaphor in windowing systems
        • Microsoft Bob: metaphor gone too far. Does the desktop need to reflect your bedroom, or your workspace?
      • Assembly-line metaphor for a new car configurator
      • Shopping-cart metaphor for online shopping
      • Cassette tape player for music player
      • Stacked transparencies metaphor for layers in a graphics editor
      • Recycling bin metaphor for deleting files
    • Given an idea for a metaphor, analyze the contrasting features of source and target domain
    • Analyze relationship between features
      • too many features from base domain results in conceptual baggage
      • Too few features leads to confusion, poor mapping, poor metaphor
    • Experience to see if people can use metaphors to derive expectations of behaviours

CS349, 2017-05-12

Visual Design

You need to present the elements of your interface to the user. User needs to know

  • What can I do in this interface?
  • Where is the thing I’m looking for?
  • What is expected of me?
  • What is related to what?

The program wants to impose as little thinking as possible on the user. Allow them to concentrate on the task, not the interface

  1. Highest level design goals
    • Make supported actions clear
    • Create desired relationships and avoid undesired relationships
  2. Create a presentation that…
    • Has an attractive look
    • Is easy to understand at a galance
    • Has a distinctive, recognizable look.
  3. Avoid a presentation that…
    • Is cluttered/hard to organize
    • Is hard to perceive clearly
    • Contains excessive idiosyncrasy
    • Makes the user stop to think about avoiding errors

Design with the human brain’s conscious and unconscious capabailities in mind

  1. Keep things simple
    • people have limited cognitive processing power
  2. Leverage pre-attentive processes
    • make design seem intuitive, obvious, and focused

Pre-attentive processes

  • Happen at a lower level than conscious thought
  • Do a huge amount of work out of sight, and gives your conscious mind the results

Simplicity

In anything at all, perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away.

Antoine de Saint Exupery

  • Present the minimum amount of information to achieve maximum effect
  • Simplicity leads to quickly recognized and understood functionality
    • Less information means less process time
    • Can produce correct mental models more effectively/quickly
  • Simplicity also aids recall
    • Less to remember. Easier to retain critical information

To achieve simplicity, reduce, reduce, and reduce.

Organization and Structure

Gestalt Principles

  • Structure doesn’t occur naturally. It must be explicitly created and designed
  • People will find order, even if none was intended
    • Don’t just throw elements into a UI
  • Need to explicity create the structure
    • Consciously consider what placement and arrangement communicates to the user
  • Gestalt principles can help with this. Theories of visual perception that describe how people tend to organize visual elements into groups or unified wholes
  • Clues about how the brain groups raw visual output
Proximity

Individual elements are associated more strongly with nearby elements than those further away * e.g. spacing stars more closely vertically gives the impression of columns. Closer horizontally gives the impression of rows.

Similarity

Elements associate more strongly when they share basic visual characteristics, such as

  • shape
  • size
  • colour
  • texture
  • orientation
Good continuation

Our visual system is biased to perceive continuous forms rather than disconnected segments

  • Elements arranged in a straight line or smooth curve are perceived as being more related than elements not on the line or curve.
  • See slides 22-24
Grouping v. Ambiguity

Closure

We tend to see a complete figure even when parts of the information is missing. We tend to perceive a set of individual elements as a single, recognizable pattern, rather than multiple individual elements.

  • Generally, we can fill in the gaps.
    • e.g. Positive/negative designs
    • e.g. Cascading windows: even without a distinct border on each window, we can usually recognize the borders of a window based on the content in the window
Figure/Ground

Our mind separates the visual field into the figure and the ground

  • Figure is the visual element that is interpreted as being the object of interest
  • Ground is the area on which it rests (and everythign else)
Law of Pragnanz

We tend to interpret ambiguous images as simple and complete, versus complex and incomplete

  • Ambiguous images: those that can be interpreted in more than one way
  • Images recalled from memory are simplified
  • Design
    • Minimize the number of elements
    • Symmetrical composition is perceived as simpler
Uniform connectedness

Elements connected to one another by uniform visual properties are perceived to be more related than elements that are not connected

Two typical strategies

  1. connecting lines
  2. common regions
Alignment

Not necessarily a Gestalt principle, but it is a powerful organizing tool

  • Some in the design community include it, but it doesn’t appear in the original lierature
    • for exams, it is

CS349, 2017-05-15

Visual Design, cont’d

Pleasing Layouts

Gestalt principles applied to user-interface layouts

  • Lots in common with graphic design
  • Four principles
  1. Proximity

Items relating to each other should be grouped close together. When several items are in close proximity to each other, they become one visual unit … This helps organize information and reduces clutter

Williams, p. 14

  1. Alignment

Nothing should be placed on the page arbitrarily. Every element should have some visual connection with another element on the page. This creates a clean, sophisticated, fresh look.

Williams, p. 14

  • Examples, edge alignment and center alignment
  1. Repetition

Repeat visual elements … throughout the piece. You can repeat colour, shape, texture, spatial relationships, line thicknesses, sizes, etc. This helps develop the organization and strengthens the unity.

Williams, p. 14

  1. Contrast

The idea behind contrast is to avoid elements on the page that are mearly similar. If the elements (type, colour, size, line thickness, shape, space, etc) are not the same, then make them very different. Contrast is often the most important visual attraction on the page.

Williams, p. 14

Applying Concepts

Common Mistakes
  • Haphazard layout (no explicit design)
  • Aligning labels, not controls
  • Bounding boxes create clutter and compete for attention
Testing it out
  • Show it to someone else
    • Don’t ask if they like it, ask why.
    • Try to get first impressions
      • First impressions define whether or not the interface is good. You can’t afford to rely on people “warming up” to your designs
  • Use the squint test
    • Mimics early portion of visual recognition system
Impact
  • Good visual design can reduce human processing time
  • Tullis redesigned lodging information screens (1984)
    • 5.5s v. 3.2s average search times
Summary
  • Strive for simplicity
  • The Gestalt principles provide insights into the pre-attentive processes in the brain
  • Use the principles to struture a visual design by…
    • grouping visual information into higher-level units
    • establishing relationships between related eleemnts
  • Don’t leave visual design up to chance
    • Think about your design
    • Test it out

CS349, 2017-05-17

Design

A Design Process: User-Centered Design

To make things usable and useful, you need to understand the people who use your software

The philosophy

  • Ask real people what they need
  • Ask people what problems they have with current solution
  • Think about the people who will use your software
  • Test your ideas with people

Developers are not people

Some History

Refined at Apple, with the Mac user-interface

Process

  • User studies: bring in users, provide mockups, assess
  • Implementation: iterate based on (agile) feedback
    • Fix problems, update solutions, etc
  • Usability studies: more users, more video, more analysis

Problems

  • Time: adds 1-2 years to the development cycle
  • Changes: no “cutoff” for changes!

Solutions

  • Manage through iteration (Agile process)
Principles
  1. Understand the user’s needs
    • Build a product that meets real needs rather than building it because it can be built
  2. Design the UI first
    • Design the UI first, and then design the architecture to support the UI
  3. Iterate
    • You won’t create the best UI design on the first tr
    • A great design requires attention
  4. Use it yourself
    • You’ll find obvious problems that can be fixed while it’s still easy to fix
      • If the development process goes too far, there are too many dependencies. It becomes difficult to make certain changes based on a lack of isolation
  5. Observe others using it
    • It’s critical to observe other people using your UI in a realistic way very early in the development cycle

We will not focus much on the “Design the Architecture”, “Choose a set of scenarios”, “Implement the Scenarios” sections.

A) Understand the user
  1. Observe existing solutions
    • As well as what’s wrong with them
  2. List scenarios
    • Literally all the things your users want/need to do
    • Scenarios
      • are stories of people undertaking activities with technology
      • they are a natural way to think
        • easy to understand (for devs and users)
        • contain sequencing data(?)
      • must be refined/elaborated with appropriate detail
        • exactly what the user does
        • how UI changes in response
      • have pitfalls:
        • typically crowds out the exceptional use-cases and users
        • often fail to catch “oughts”
        • cannot be formalized (this is also a strength)
      • have variations
      • should be retained
        • written v. memorized v. generated on demand
  3. List functions required by scenarios and prioritize functions
    • Some functions will be required by several scenarios
    • Prioritize
      • Critical, Important, or Nice to have
  4. List functions by frequency and commonality
    • Frequent use by many
      • Visible, few clicks away
    • Frequent use by few
      • Suggested, few clicks
    • Occasional by many
      • Suggested, more clicks
    • Occasional by few
      • Hidden, more clicks away
B) Design the UI
  • Identify/design widgets (components) and widget types to support prioritized functionality
    • e.g. text fields, buttons, etc
  • Balance functionality with well-understood widget types
    • i.e. customized control v. familiar controls
  • Assign attributes
    • Model
      • what data does it need
    • Affordances
      • what can you do with it?
    • Presentation
      • how does it appear in the UI?

Component Distribution

  • Temporal distribution
    • When components appear, the flow from one interface to another
  • Spacing distribution
    • Where components appear on an individual interface section
    • Use visual design & Gestalt principles

Design the flow of the UI. Which screens lead to which, etc

Storyboards

  • Quick way to sketch out sequences and schematics
    • could form the basis of a paper prototype
  • Typically linked to a scenario

Macro and Micro Structure

  • Interaction Sequences
    • macro-structure, convey the big picture of system interaction
    • e.g. Phone Book – Add New Entry –> Edit Entry – Submit –> Match to Existing Entry
    • uses labeled boxes and arrows, but sometimes a more extensive visual vocabulary may be helpful
  • Interface Schematics
    • micro-structure, convey essentials and functionality at individual steps of interaction

Need both to describe a user interface

Visual Vocabulary

  • A standard set of graphical symbols and notation to describe something
  • Qualities of a good UI design visual vocabulary
    • Whiteboard-compatible
    • Tool-indepedent
    • Small and self-contained
  • The UML tends to be too formal (too “high ceremony”)
  • Jesse James Garret’s visual vocabulary
    • Good, but web-centric
  • Find a consisten visual vocabulary that works for you

Interface Schematics

  • Includes enough detail so that someone could begin designing and implementing system logic
    • visual arrangement of content/information
    • functionality of interface (widgets, forms, data)
    • navigational and content elements ordered to convey structure and meaning
    • indicates the relative significance of all elements
  • Interface schematics are not the same as
    • graphic design mockup
    • paper prototypes
  • See notes for examples on interface schematics

For a list of wireframe drawing tools and image editing software, see course notes [29]

CS349, 2017-05-19

PROTOTYPING

  • Iteration and refinement
  • Might take successive versions to “get it right”

Process

  • User studies
    • bring in users, provide mockups, assess
  • Implementation
    • iterate based on feedback
  • Usability studies
    • more users, video, analysis

A limited representation of a design that allows people to interact with it and explore its suitability

  • Goal: Maximum Feedback, Minimum Effort

Examples

  • paper sketches/collage with “human computer processor”
  • slide show or video simulating the use of a system
  • physical model (wood, cardboard, etc.)
  • software or hardware with limited functionality
Prototype Objectives

Build “working” prototype from design work

  • Aid in discussions with stakeholders
  • Help communication of ideas among team members
  • For user evaluation
  • For technical/layout testing and fine-tuning
What to Prototype?

Difficult, controversial, and critical areas

Possible aspects to test

  1. Concepts and terminology
  2. Nagivation, task flow
  3. Mental models
  4. Documentation, help
  5. Layout, colours, fonts, graphic elements, “brand”
  6. Custom widgets
  7. Performance metrics
  8. Technical feasibility
  9. Usefulness
Fidelity

Faithfulness of prototype appearance and performance to final product

  • Low
    • prototype doesn’t look much like the final product. Operation may be simulated and slower
  • High
    • prototype looks and operates like the real product
Paper Prototyping

Usability Testing where representative users perform realistic tasks by interacting with a paper version of the interface that is manipulated by a person playing computer, who doesn’t explain how the interface is intended to work.

Snyder, 2003, p. 4

Wizard of Oz Technique

Evaluate unimplemented technology by using a human to simulate the response of a system

  • Much easier to do this technique than implement complex features
Paper Prototyping Image Quality
  1. Rendering: How good should it look?
    • Good enough to elicit feedback about critical/risky design issues
  2. Creation speed is of the essence
  3. Modifications: When?
    • While user is present
    • Get immediate feedback. Make changes without losing users’ context
    • Consider allowing the user to make changes
  4. Coding effort in paper prototyping is always zero
  5. No code to write or rewrite until design is stabilized
Interactive Prototyping

Example

Tools

  1. Figma
  2. Axure RP
  3. Sketch
  4. inVision
  5. UXPin
Summary

Usability and usefulness are important properties that don’t just happen. User Centered Design is a process:

  • Understand the user needs
  • Design the UI first
  • Iterate on design
  • Use it yourself
  • Observe others using it

CS349, 2017-05-23

WINDOWING SYSTEMS

Windowing functions Base Window System v. Window Manager

GUI Characteristics

  • GUI architectures share common characteristics
    • support output to a graphical display
      • display text/high-resolution graphics
    • Handle user input from multiple devices
      • minimally, keyboard (text) and a positional input device (mouse)
    • Provide an interface to display/manipulate content
      • Most modern GUIs use a desktop metaphor
        • windows contain data and can be manipulated (resized, moved, overlap, etc)
      • Common GUI elements: scrollbars, buttons, etc
  • A windowing system provides input, output, and window management capabilities to the operating system
    • Before windowing systems, systems typically ran a single application, which dominated the screen (DOS, BIOS, etc)
    • With windowing systems, programs can run simultaneously, each with their own separate window. Windows may exist side-by-side, or overlap. Input is directed to the focused/correct window by the windowing system

Base Window System (BWS)

  • Lowest level abstraction for windowing system
    • routines for creating, destroying, and managing windows
  • Routes mouse and keyboard input to correct window
    • only one window has focus to receive input
  • Ensures only one application changing frame buffer (video memory) at a time
    • one reason single-threaded/non-thread-safe GUI architectures are popular
  • The BWS provides each program with a window, and manages access to that window
    • the BWS provides a drawing canvas abstraction
    • The application is shielded from details of frame buffer, visibility of the window, and all other application windows
    • each window has own coordinate system
      • BWS transforms between global (screen) and local (window) coordinate systems
      • Each window does not need to worry where it is on screen. Its top-left is (0,0)
    • BWS provides graphics routines to the program for drawing

Window Manager

  • Provides conceptually different functionality
    • layered on top of BWS
    • provides interactive components for windows (menus, close box, resize capabilities)
    • creates the look and feel of each window
  • Application “owns” the contents of the window, but the window manager owns the application itself

Application Window v. Application “Canvas”

  • The window manager owns the window (including its controls)
    • the close, minimize, fullscreen buttons
    • the application title
    • the window frame
  • the application owns the canvas

Types of Window Managers

  1. Tiling Window Manager
    • paints all windows by placing them side-by-side or above and below each other
    • There is no window overlap
  2. Stacking Window Manager
    • Allows windows to overlap by drawing background windows first, then drawing the foreground windows on top of them
  3. Compositing Window Manager
    • Lets all windows be drawn separately, and then puts them all together and draws them all using 2D or 3D techniques
    • More complex, but provides extra functionality
      • e.g. cascading visuals when alt-tabbing
      • e.g. partial transparency of windows

BWS v. Window Managers

  1. Unixes and Linuxes
    • separate the BWS and window manager
      • separation of BWS from WM:
        • enables many alternative looks and feels for the windowing system
        • one of the keys to X11’s lasting power: can innovate by changing the WM layer
        • resiliency, since BWS and WM are separate processes
    • BWS: X Window System
    • Stacking WM: Fluxbox, Openbox, Window Maker, etc
    • Compositing WM; Compiz, KWin, etc
  2. Windows Vista, 7, 8, 10 and MacOS combine the BWS and WM. Or, at least, doesn’t distinguish between the two
    • Windows; Desktop Window Manager (BWS & Compositing WM)
    • MacOS; Quartz Compositor (BWS & Compositing WM)
    • Trade-offs in approaches?
      • Look and feel
      • Window management possibilities
      • Input possibilities

Conceptually, on both platforms, there is a separation of canvas (assigned to application) and window decoration/OS overlay handled by window manager

  • Lines between do blur when combined, however
  • e.g. Windows fast access menu-bar in the window frame

X Windows (X11) System

  • Base windowing system, separate from the operating system
    • not a window manager
    • does not specify the style of user interface
  • What does it do?
    • A protocol to create windows, handle input, draw graphics
    • A standard for low-level graphical output and user input

Design Criteria

  1. Implementable on a variety of displays
  2. Applications must be device independent
  3. Must be network transparent
  4. Support multiple, concurrent application displays
  5. Support many different applications
  6. Support output to overlapping windows (even when partially obscured)
  7. Support a hierarchy of resizable windows (an application can use many windows at once)
  8. High performance, high-quality text, 2-D graphics, imaging
  9. System should be extensible

Displays, Screens, Windows

  • In X, a display may have multiple screens
  • A display may have multiple windows
  • A window may cross multiple screens

X Client-Server Architecture [27]

Structure of a Typical X Program

  1. Perform client initialization
  2. Connect to the X server
  3. Perform X related init
  4. Event loop
    • get next event from the X server
    • handle the event
      • if the event was a quit message, exit
      • do any client-related work
    • send drawing requests to the X server
  5. Close down the connection to the X server
  6. Perform client cleanup

Xlib, an X Windows Library, is provided [s31]. Note that X is relatively complex.

Contrast: Opening a Window in Java

import javax.swing.\*;

public class TestWindow extends JFrame {
    public TextWindow() {
        this.setTitle(...)
        this.setDefaultCloseOperation(JFrame.EXIT\_ON\_CLOSE);
    }
    public static void main(String args[]) {
        TestWindow myWindow = new TestWindow();
        myWindow.setSize(400,300);
        myWindow.setVisible(true);
    }
}

Recap: X Windows Design

  • Much of XWindows architecture was influenced by its time period
    • larger server machines and low-cost client displays because computation was expensive
  • As computation got cheaper, certain aspects of program behaviour could be assumed
Appendix: Running X11 sample code [35]. Not covered in lectures/exams

CS349, 2017-05-24

MODERN GUI SYSTEMS

JAVA GUI PROGRAMMING

A quick-start guide to building Swing applications

The Java Platform

Everything Is A Class
  • Classes, objects are core language constructs
  • Object-oriented features
    • polymorphism, encapsulation, inheritance
  • Static and member variables and methods
  • Resembles C++
    • Differences
      • no pointers
      • no type ambiguity
      • no destructor
      • single inheritance model
JDK [L7_S14]
Classes and Packages [S8_S16]
Class Hierarchy
  • Implicit class hierarchy
    • All classes in Java are derived from the Object class
      • clone(), toString(), finalize()
    • Classes you write will inherit this basic behaviour

Initiating Objects

  • Primitive types are allocated on the stack, passed by value
  • Objects are allocated on the heap, passed by reference
    • technically, the value of address passed on the stack, but this behaves like pass-by-reference
    • practically, this means you don’t need to worry about pointer semantics in parameter passing
      • Bicycle my_bike = new Bicycle();
      • Bicycle kids_bike = my_bike
        • both refer to the same memory on the heap

Composition: Inner Classes

class ShadowTest {
    public int x = 0;

    class FirstLevel {
        public int x = 1;

        void method(int x) {
            print("ShadowTest.this.x="+ShadowTest.this.x);
            // 0
            print(x); // watch the scope
            // 23
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel f = st.new FirstLevel();
        f.method(23);
    }
}

Inheritance & Subtype Polymorphism

Increase code reusability by allowing a class to inherit some of its behaviour from a base class (“is-a” relationship)

  • In Java, this is done by using the keyword extend
  • Abstract classes can be extended. Their abstract methods must be implemented by the inheriting class, less the inheriting class is also abstract

Java only supports single inheritance

  • In practice, this simplifies the language
    • the “Diamond Problem”
      • class D inherits from B and C
      • classes B and C inherit from class A
      • D inherits A twice?
  • It’s very common in Java to derive an existing class and override behaviour
  • All classes have Object as their ultimate base class (implicit)

Interfaces

An interface represents a set of methods that must be implemented by a class (a contract or blueprint). Somewhat similar to pure abstract classes/methods

  • Cannot be instantiated
  • Class implementing the interface must implement all methods in the interface
  • Uses implements keyword

In Java,

  • extend a class to derive functionality from it
  • implement an interface when you want to enforce a specific API

BUILDING USER INTERFACES

  • Swing components
  • Creating a window
  • Adding Swing components

Java UI Toolkits

  1. AWT (1995)
    • “Heavyweight” with platform-specific widgets
    • AWT applications were limited to common-functionality that existed on all platforms
  2. Swing (1997)
    • “Lightweight”, full widget implementation
    • Commonly used and deployed cross-platform
  3. Standard Window Toolkit (SWT, ~2000)
  4. Java FX (~2010)
    • Cleaner and richer than Swing
    • Intended for rich desktop+mobile applications
    • Still seeking market space

Building a Swing UI

  1. Create a top-level application window using a Swing container
    • JFrame or JDialog
  2. Add Swing components to this window
    • typically, you create a smaller container (like JPanel) and add components to the panel
      • this makes dynamic layouts easier
  3. Register for events
    • add listeners, like keyboard presses and mouse moves/clicks
    • implement actual behaviour for event callbacks
  4. Make components update and paint themselves based on events

Creating a Window

import javax.swing.\*;

public class BasicForm1 {
    public static void main(String[] args) {
        // create a window
        JFrame frame = new JFrame("Layout Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // create a panel and add components
        // all Swing components are types of JComponent
        JPanel panel = new JPanel();
        JButton b = new JButton("OK");
        panel.add(button);
        frame.add(panel);

        frame.setResizable(false);
        frame.setSize(200,200);

        frame.setVisible(true);
    }
}

Open a Window [L8_S36]

Add a Component [L8_S37]

CS349, 2017-05-26

BASIC GUI DRAWING

Local Coordinates

  • Any modern OS manages multiple windows
  • Base Window System manages
    • where the window is located
    • whether it is covered by another window, etc
    • enables drawing using local coordinate system for the window

Conceptual Drawing Models

  1. Pixel
    • SetPixel(x,y,colour)
    • DrawImage(x,y,w,h,img)
  2. Stroke
  3. Region

DRAWING IN JAVA

  • Overriding painComponent()
  • Graphics object

Graphics and Painting

  • Applications consist of a JFrame (window), containing one or more Swing components
  • We often define a top-level canvas (container)
    • this can hold other components
      • text fields, buttons, scrollbars, etc
    • we can also draw directly on the canvas
  • Each component has a paintComponent() method, which describes how it paints itself
    • You can override this method, and draw primitive objects using the java.awt.Graphics object (basically, the Graphics Context)
    • This is a common technique for defining drawables in Java
  • see L9_S21,22 for some code

EVENTS

  • User interface architectures need to be able to accept input from real-world devices, and map them to actions within a system
    • support the transformation of input into commands
    • we want a general, reusable architecture that supports multiple devices

Event-Driven Programming

Event-driven programming is a paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs/threads.

Wikipedia

  • An event is a message to notify an application that something happened
    • e.g key press, key release, mouse move, mouse click, focus gained, focus lost, timer done, etc.

Role of the BWS, WM

  1. Collect event information
  2. Put relevant information in a known structure
  3. Order the events by time
  4. Decide which application and window should ge the event
  5. Deliver the event

Role of the Programmer

  1. Indicate what events you are interested in to the BWS/WM, to ensure that events are delivered
  2. Write code
    • register to receive events
    • receive and interpret those types of events
    • update program content based on event
    • redraw the display (provide feedback) to communicate to the user what had changed
  3. In modern languages, the process of registering for events and handling events is simplified
    • Java: Listener model
    • C#: Delegate model
    • Javascript: Something else

Event Dispatch

Event Capture, processing, and dispatch

  • The event dispatch stage includes
    • Event dispatch
      • getting events to the correct widget
    • Event handling
      • running code for an event
    • Notify view and windowing system
      • MVC, and view notification
  • The Event loop is the primary mechanism for event dispatch within an application
    • the event loop can be managed by application (XLib) or the toolkit (JVM)
    • the event loop iterates through all events in the event queue, and pushes them in order to the appropriate application
    • the application needs to determine which component should process the event
    • widget are often the final target of events dispatched from the event loop
  • Once delivered to a widget, it still needs to interpret what any of the input means in the proper context and react appropriately

Widget Layout

  • In complex applications, widgets are often laid out in a hierarchy
    • We call this hierarchy an interactor tree
    • Container classes and low-level components are nested together
    • Dispatching an event to the correct widget (that can handle the event) means traversing this tree

Lightweight v. Heavyweight Widgets [L10_S17]

Heavyweight widgets
  • Widget toolkit wraps native-OS widgets
  • BWS/OS provides a hierarchical “windowing” system for all widgets across all applications, and treats a widget essentially as a window
  • This allows the BWS to dispatch events to a specific widget (and not just the top-level window)
  • nested X Windows, Java’s AWT, standard HTML form widgets, Windows MFC
Lightweight widgets
  • The widget toolkit draws its own widgets and is responsible for mapping incoming events to widgets
  • BWS/OS provides a top-level window only, and can only dispatch to the window (NOT the widget)
  • Java Swing, JQuery UI, Windows WPF

Positional Dispatch

  • Send input to the widget under the mouse cursor
  • The front-most widget under the cursor should receive the event

Widgets can overlap, so how do we determine the appropriate target widget?

Bottom-up positional dispatch
  • Event is first routed to leaf node widget in the interactor tree corresponding to location of mouse cursor
  • Leaf node has first opportunity to act on that event
  • The leaf node widget can either
    • process the event itself
    • pass the event to its parent (who can process it and/or send it to its parent)
      • Why would a widget pass an event to its parent?
      • e.g. a palette of colour swatches may implement the colours as buttons. But palette needs to track the currently selected colour. This is easier if the palette deals with the events, rather than the button
Top-down positional dispatch
  • Event is routed to widget in the highest-level node in the interactor tree that contains the mouse cursor
    • can process the event itself
    • can pass it on to a child component
  • Key idea is that the highest-level node has the first chance at acting on the event
    • can create policies enforced by the parent
      • e.g. stopping events if all children are disabled
    • supports relatively easy logging of events for later replay
Limitations

Positional dispatch can lead to odd behaviour

  • Example, we normally send keystrokes to scrollbar if the mouse is over the scrollbar
    • What if the mouse-drag starts in a scrollbar, but moves outside of it as it drags? Do we continue sending the events to the scrollbar? To the adjacent widget instead?
    • What if the mouse-press event occurs over one button but the release is over another widget? Does each widget get one of the events?
  • SOmetimes, position isn’t enough. Also need to keep track of focus

Focus Dispatch

Accelerator Key Dispatch

Toolkit Summary

  • BWS and widgets cooperate to dispatch events
    • heavyweight
      • BWS has visibility into all widgets in the application
      • BWS can dispatch top-down or bottom-up
    • lightweight
      • BWS can dispatch top-down only
      • toolkit dispatches to the widget
        • in Java, the JVM manages the dispatch

Dispatch Summary

  • Mouse-down events are almost always positional
    • dispatched to widget under cursor (top-down or bottom-up)
  • Other mouse and keyboard events go to widget in focus
  • Positional and focus dispatch work together

CS349, 2017-05-29

Event Handling

How to manage event-code binding

  • Switch Statement Binding
  • Inheritance Binding
  • Event Interfaces & Listeners
  • Delegate Binding

After dispatch to a widget, how do we bind an event to code?

Event-to-Code Binding

How do we design our GUI architecture to enable application logic to interpret events once they’ve arrived at the widget?

  • Design Goals
    • Easy to understand (clear connection between each event and code that will execute)
    • Easy to implement (binding paradigm or API)
    • Easy to debug
    • Good performance

Event Loop and Switch Statement Binding (X11)

All application events are consumed in one event loop (not by the widgets themselves)

  • Outer switch statement selects window and inner switch selects code to handle the event
  • Used in Xlib, Apple System 7, and, until recently, Blender
WindowProc Binding (MS Windows)
  • Each window registers a WindowProc function (Window Procedure) which is called each time an event is dispatched
  • The WindowProc uses a switch statement to identify each event that it needs to handle
    • there are hundreds of standard events

Inheritance Binding

Java Event Handling

Java simplifies much of event handling

  • Events are transmitted to onscreen objects without programming intervention
  • The event loop is hidden and managed by the JVM
  • To handle events, tell onscreen objects what you’re interested in and what to do when the event fires.
Inheritance Binding (Java 1.0, OSX)

Event is dispatched to an Object-Oriented Widget

  • These widgets inherit from a base widget class with all event handling methods defined a priori
    • onMousePress, onMouseMove, onKeyPress, etc
  • The widget overrides methods for events it wishes to handle
    • each method handles multiple related events
Inheritance Problems
  1. Each widget handles its own events, or the widget container has to check what widget the event is meant for
  2. Multiple event types are processed thru each event method
    • complex and error-prone
    • another switch statement
  3. No filtering of events
    • performance issues (esp. with frequent events)
  4. Does not scale well. How do we add new events?
    • e.g. penButtonPress, touchGesture
  5. Muddies separation between GUI and application logic
    • event handling application code is in the inherited widget
    • Use inheritance for extending class functionality, not for binding events

Event Interfaces & Listeners

Rather than a subclass widget, define an interface for event handling

  • Here, an interface refers to a set of functions or method signatures for handling specific types of events
    • e.g. in Java, can define an interface for handling mouse events
  • Can then create a class that implements that interface by implementing methods for handling these mouse events
  • Widget object implements event “listener” interfaces
    • e.g. MouseListener, MouseMotionListener, KeyListener, etc
  • When event is dispatched to widget, the relevant listener method is called
Improvements
  1. Each event type assigned to an event method
  2. Events are filtered
    • only sent to object which implements interface
  3. Easy to scale to new events
Problems
  1. Each widget handles its own events, or widget container has to check what widget the event is meant for
  2. Muddies separation between GUI and application logic
    • event handling application code is in inherited widget
Listener Object Binding

MouseListener Implementation [L10_S48]
...
Listener Adapter Pattern
  • Many listener interfaces have only a single method
    • e.g. ActionListener only has actionPerformed()
  • Other listener interfaces have several methods
    • Typically, only interested in a few of them, not all
    • This leads to lots of boilerplate code with no-op methods
  • Each listener w/ multiple methods has an adapter class with no-op methods
    • Simply extend the adapter, overriding only the methods of interest

Delegate Binding

Interface architecture can be a bit heavyweight

  • Can instead have something closer to a simple function callback
  • Delegates in Microsoft’s .NET are like a C/C++ funciton pointer for methods. However, they are
    • Object-oriented
    • Completely type-checked
    • More secure
    • Support multicasting (able to point to more than one method)
  • Using delegates is a way to broadcast and subscribe to events
Using Delegates
  1. Declare a delegate using a method signature
  2. Declare a delegate object
  3. Instantiate the delegate with a method
  4. Invoke the delegate
Multicasting
  • Instantiate more than one method for a delegate object
    handler = MyMethod1 + MyMethod2;
    handler += MyMethod3;
    
  • Invoke the delegate, calling all methods
    handler("Hello");
    
  • Remove method from a delegate object
    handler -= MyMethod1;
    
  • How about
    handler = MyMethod4;
    

Event Handling in Java [L10_S65]

CS349, 2017-05-31

ANIMATIONS

A simulation of movement created by displaying a series of pictures, or frames

  • Animation: drawing frames at a consistent rate
  • Goals
    • Move things around on the screen
    • Repaint 24-60 times per second
    • Make sure events are handled on a timely basis
    • Don’t use more CPU than necessary
    • Easily understood code

Cats Eyes X style

public void eventLoop() throws InterruptedException {
    while (true) {
        if (this.myEventQueue.hasEvents()) {
            this.handleEvent(this.myEventQueue.nextEvent());
        }
    }
    this.handleAnimation();
    this.paintComponent(this.getGraphics());
    Thread.sleep(1000/this.FPS);
}

Why do the eyes move slower than the mouse?

  • There is one event per pixel moved. We update the frames 30 times per second, but there’s too many events to process!
    • solution could be to separate the event handling speed and the frame handling
      • let the thread sleep only when there are no events to process(?)

Screen Flicker During Drawing

  • Suppose you are animating two balls on the display in a game.
  • As the balls get closer, you notice that one seems to flicker.
    • If you paint balls sequentially, then you might clear a rectangle of the first ball’s position, paint the first ball in the new position, then clear rect for the second ball and paint the second ball.
    • Ball 1 has a bite taken out of it or maybe even vanishes until next update

Flickering: when an intermediate image is on the display

  • Need to ensure that only complete images are drawn
  • Solution
    • Create an off-screen image buffer
    • Draw to the buffer
    • Copy the buffer to the screen as quickly as possible (between refreshes)
  • In X, this is a manual process
  • In most other situations, it is done for you

Double Buffering [L11_S12]

Java Code: Double Buffering

  • Modern toolkits often have double-buffering built-in
    • e.g. in Java Swing, it is built into the JComponent class (which is a base class for all/most drawable components, so they inherit this functionality)

public boolean isDoubleBuffered() public void setDoubleBuffered(boolean o)

  • Double-buffering is enabled by default!
    • if set in top-level container, all subcomponents will be doubled buffered, regardless of individual settings

Java: Animation Using a Timer in Java

class ColouredX extends JComponent {
    ...
    private Point ballPos = new Point(100, 0);
    private final int FPS = 40;
    private Timer timer;

    public ColouredX() {
        this.addMouseListener(...);
        this.timer = new Timer(1000/FPS, new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                ballPos.y += 2; repaint();
            }
        });
        this.timer.start();
    }

    /* Paint ball in new location */
    public void paintComponent(Graphics g) {
        ...
        g2.setColor(Color.ORANGE);
        g2.fillOval(this.ballPos.x, this.ballPos.y, 30, 30);
    }

Note

  • If you adjust your frames per second, be careful you may also be adjusting the number of updates for second.
    • If you start updating more frequently, your object will move faster, since you’re using less time to translate the same distance
  • Assignment 2 involves improving animations

Model-View-Controller

Observations

  • When one view changes, other(s) often need to change as well.
    • Ideally, we want a single representation of the underlying data, and multiple views of that data
  • The user interface code probably changes more and faster than the underlying application
    • many recent changes in MS Office were to UI code
    • Excel’s underlying functions and data structures are probably very similar to Visicalc, the original spreadsheet
  • How do we design software to support these observations?

Possible Design: Tight Coupling

Cell\[\]\[\] cells;
    \+ void setCell(...)
    \+ Object getCell(...)
    \- void paintGraph(...)
    \- void paintTable(...)
    \- void paint(...)
  • Issues with bundling everything together
    • What if we want to display data from a different type of source?
      • e.g. Database
    • What if we want to add new ways to view the data?
  • Primary problem
    • Tight coupling of data and presentation prevents easy modification and extension

CS349, 2017-06-02

Observer Design Pattern

MVC is an instance of the Observer design pattern

  • Provides a well-defined mechanism that allows objects to communicate without knowing each other’s specific types
    • promotes loose coupling
  • Related to
    • “publish-subscribe” pattern
    • listeners
    • delegates in C#

CS349, 2017-06-05

Widgets

A generic name for parts of an interface that have their own behaviour

  • e.g. buttons, progress bars, sliders, etc
  • Widgets are also called components or controls
    • they control their own appearance
    • they receive and interpret their own events
  • Are often put into libraries (toolkits) or reuse
    • Software bundled with a window manager, operating system, development language, hardware platform
    • The toolkit defines a set of GUI components for programmers
      • Programmers access these GUI components via an API

Heavyweight

Lightweight

Widget Toolkit Design Goals

  1. Complete
    • Complete set of widgets and functionality
    • Goal: GUI designers have everything they need
  2. Consistent
    • User: Look and Feel is consistent across components
    • Developer: Consistent usage paradigms
  3. Customizable
    • Developer can reasonably extend functionality to meet particular needs of application

Meeting these requirements encourages reuse

Completeness

The Macintosh 7 had a button, slider, pull-down menu, checkbox, radio button, text entry fields, and a file I/O widget.

  • Java Swing has many, many more.
    • SwingSet Demo
      • shows lots of different widgets with lots of variations
      • can easily view source code
        • to run, download examples, and run $ ant SwingSet2
Consistency

Facilitate learning by

  • Using a common look and feel
    • Look: consistent visual appearance
    • Feel: consistent and expected behaviour
  • Using widgets appropriately

Consistency helps users anticipate how the interface will react, and promotes easier discoverability of features

  • For example, users familiar with Windows Vista will/can recognize features of the Vista platform.
  • This is not very transferable to Java Swing, because Swing isn’t very recognizable in general.
  • Moreover, people expect widgets to behave in certain ways
    • When we want to “Confirm” authentication, for example, we expect to left-click an Ok or Agree button, not right-click some obscure widget.
      • User should not guess
Customizable

How do we customize widget behaviour and appearance?

  1. Properties
    • e.g. change colour, font, orientation, text formatter, …
  2. Factor our behaviour (Pluggable behaviour)
    • Responding to an action: ActionListener
    • Swing’s UIManager for changing look and feel
    • JTable example

More on customizability later

Widgets as Input Devices

CS349, 2017-06-07

LAYOUTS

Two-Inteface Layout Tasks

  1. Designing a spatial layout of widgets in a container
  2. Adjusting the spatial layout when container is resized
    • Both can be done by hand (ie. graphic design)
    • or automatically (ie. with algorithms)

Spatial layout is one component of visual design

  • It should use/maintain Gestalt principles
  • It should use/maintain grouping, hierarchy, relationships, balance to achieve organization and structure

Dynamic Layout

  • If a window is resized, we want to maximum use of available space for displaying widgets
  • Hoeever, we want to do this such that the window maintains consistency with spatial layout
    • and preserves visual quality of spatial layout
  • Need to dynamically modify the layout
    • reallocate space for widgets
    • adjust location and size of widgets
    • perhaps even change visibility, look, and/or feel of widgets

Moreover, widgets should be flexible to adjust for different screen sizes

Layout Managers

  • A layout manager provies a layout algorithm to size and position its children widgets
    • Swing’s package provides a number of them
      • Grid, Box, Border, Flow, GridBag, etc…
  • A widget can set the most appropriate layout strategy
    • container.setLayout(new GridLayout(2,3))
  • Layout Managers are most useful for container widgets like JPanel or JScrollPane
BorderLayout
  • Places components in up to five areas
    • top, bottom, left, right, center
BoxLayout
  • Puts components in a single row or column
CardLayout
  • Lets you implement an area that contains different components at different times
FlowLayout
  • Simply layous out components in a single row, starting a new row if its container is not sufficiently wide
GridBagLayout
  • Flexible layout manager
  • Aligns components by placing them within a grid of cells
    • Allows components to span more than one cell
GridLayout
  • Simply makes components equal in size and displays them in the requested number of rows and columns
GroupLayout
  • Developed for use by GUI builder tools, but can be used manually
  • Works with the horizontal and vertical layouts separately
  • Layout is defined for each dimension independently
SpringLayout
  • Flexible layout manager designed for use by GUI builders
  • Lets you specify precise relationships between the edgers of components under its control
    • Struts
      • static in size
      • Struts between edges will remain the same when the screen size is changed
    • Springs
      • adjustable in size
      • Springs allow distances to change/adjust to screen size changes
CustomLayout

Can implement own layout manager…

Layout Design Patterns

Composite Pattern [L14_S13]
  • Specifies that a group of objects are to be treated in the same way as a single instance of an object
  • The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies.
    • implementing the composite pattern allows clients to treat individual objects and compositions uniformly
Strategy Design Pattern [L14_S15]
  • Factors out an algorithm into separate objects, allowing a client to dynamically switch algorithms
    • eg. Java Comparator “strategy” for a collection “context”
    • eg. Switching a game’s move selection algorithm from “easy” to “hard”
    • eg. Text formatter for textboxes

FixedLayout

  • Widgets have a fixed size and fixed position
  • In Java, achieved by setting LayoutManager to null
  • Where/when is this practical?
  • How can it break down even when windows aren’t resized?
    • Adding new elements means updating the other elements, which were placed manually
    • Changing locales for text may cause the given widget size(s) to be too small

Intrinsic Size Layout [L14_S19]

  • A bottom-up approach where top-level widget’s size is completely dependent on its contained widgets
    • A bit of a stronger variant to width:auto; height:auto;
  • Single pass algorithm
    • query each child widget for its preferred size
    • adjust the parent widget to perfectly contain each item
  • BoxLayout and FlowLayout use this strategy

Variable Instrinsic Size Layout [L14_S20]

Struts and Springs Layout [L14_S21]

Tips and Strategies

  • Break up UI recursively with panels that contain panels
  • Cluster components into panels based on layout needs
  • Provide a layout manager for each panel
  • Consider making each panel into a view (see MVC lecture…)
    • reduces coupling between parts of program

Custom Layout Managers

  • Sometimes, we want a more specific, non-standard layout that cannot be achieved by the default layout managers
public interface LayoutManager {
    void addLayoutComponent(String name, Component comp);
    void removeLayoutComponent(...)
    ... 
}
  • We can build our own layout to achieve our desired effects

XML

  • Many programming languages use XML to create UIs (Android esp.)
    • enables better separation of the appearance and application code
    • UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source doe and recompile
    • declaring the layout in XML makes it easier to visualize the structure of your UI, so it’s easier to debug problems
  • Potential issues
    • Android context needs to be considered (config doesn’t change(?))
    • Many XML-based layouts use absolute positioning, relative positioning, etc.
    • A lot of burder on programmer to maintain

CS349, 2017-06-14

AFFINE TRANSFORMATIONS

We can think of widgets as shape models

  • Consists of an array of points {P1, P2, ..., Pn}
  • Has properties describing how to draw it
  • eg. Button
    • Points (0,0), (10,0), (5,0), (10,5)
    • Properties
      • text=OK
      • border_width=1
      • border_colour=blue

The Interactor Tree

Describes the hierachy of widgets

  • Widget location is always specified in terms of parent’s coordinate system (ie. relative/local coordinates)
    • need to do some math before painting
    • performing hit test requires taking parent location into consideration

We will use affine transformations with an interactor tree to…

  • Manipulate and transform widgets (shape models)
  • Tell widgets how to draw themselves on-screen, relative to their parent
  • Determine if a mouse-click intersects one of these widgets in the interactor tree

How to create multiple instances of a shape?

  • Rotation + Scaling + Translation
Translate

Add a scalar to each of the components (each point of the shape)

x' = x + t(x)
y' = y + t(y)
Uniform Scaling

Multiply each component (each point) by the same scalar

x' = x * s
y' = y * s
Non-uniform Scaling

Multiple each component (each point) by a different scalar

x' = x * s(x)
y' = y * s(y)
Rotation

Each component is some function of x, y, THETA

x' = f(x,y,THETA) = xcos(THETA) - ysin(THETA)
y' = f(x,y,THETA) = xsin(THETA) + ycos(THETA)

Benefits

  • Allows reuse of objects in scenes
    • Can create multiple instances by translating model of object and re-rendering
  • Allows specification of object in its own coordinate system
    • Don’t need to define object in terms of its screen location or orientation
  • Simplifies remapping of models after a change
    • eg. Animation

Examples

Combining Transformations [L16_S11]

We want to paint the house 2x its size, up the 30 degree slanted hill

  • Strategy
    • scale
      • x=2x; y=2y;
    • rotate
      • x=2(xcos(30) - ysin(30)); y=2(xsin(30) + ycos(30));
    • translate
      • x=...+8; y=...+4;
  • If we rotated after translation, our rotation would move the house as well as rotate it, which is not what we want

Combining Transformations [L16_S16]

  • Strategy
    • Need to rotate bubble (45 degrees) about its center
      • need to translate in a way that the center of the shape is at the origin
      • translate after
    • Need to scale the size of person
      • 2X
    • Need to translate person
      • 40px, 0px
    • Need to translate bubble
      • 60px, 30px

MATRIX REPRESENTATION

Linear Algebra

  • (s) Scalar
    • a single value (usually a real number)
  • (v) Vector
    • A representation of an ordered list of numbers
    • Matrix
      • a vector arranged in rows and columns
    • Row/Column vector
      • a matrix with just one dimension
  • (P) Point
    • A fixed location in spcae (represents a position)

Legal Operations

  • vector + vector: v1 + v2 = v3
  • vector multiplied by scalar: v1 x s1 = v4
  • point minus point = P1 - P2 = v5
  • point + vector: P2 + v5 = P1
  • 2 ways to “multiply” vector by vector
    • dot product: v1 * v2 = s2
    • cross product: v1 * v2 = v6

Goal

Represent each 2D transformation with a matrix

  • This is a succinct way of expressing a single transformation that can be used to transform all of the points in our shape model
| a b |
| c d |

Multiply matrix by a column vector => apply transformation to a point

x' = ax + by
y' = cx + dy

| x' | = | a b || x |
| y' |   | c d || y |

Matrix notation also supports combining transformations by multiplication

  • ie. transformations are associative
  • We can multiply transformation matrices together
    • This single matrix can then be used to transform many points
    • Can be sent to a GPU to speed up the process

Improvements

Examination

  • Will need to be comfortable with matrix multiplication
    • given a series of transformation matricies, what is the final transformation matrix?
    • given a final transformation matrix, what were the operations?

Notes

  • Matrices are associative
    • A(BC) = (AB)C
  • Matrices are not commutative
    • AB != BC

CS349, 2017-06-16

Affine Transformations in Java

Useful Graphics2D Methods

  • AffineTransform getTransform(), void setTransform(AffineTransform Tx)
    • returns/sets a copy of the current Transform in the Graphics2D context
  • void rotate(double theta), void rotate(double theta, double x, double y)
    • concatenates the current Graphics@D transformation with a rotation transform
  • void scale(double sx, double sy)
  • void translate(double tx, double ty)

AffineTransform handles all matrix manipulations

  • A bit more control than Graphics2D

Static Methods

  • static AffineTransform getRotateInstance(double theta)
  • static AffineTransform getRotateInstance(double theta, double anchorx, double anchory)
  • static AffineTransform getScaleInstance(double sx, double sy)
  • static AffineTransform getTranslateInstance(double tx, double ty)

Concatenation Methods

  • void rotate(double theta), void rotate(double theta, double anchorx, double anchory)
  • void scale(…)
  • void translate(…)
  • void concatenate(AffineTransform Tx)

Other Methods

  • AffineTransform createInvers()
  • void transform(Point2D[] ptSrc, int srcOff, …)

Slides worth noting

  • L17_S42; RotateTriangle.java

Scene Graphs

  • A mechanism for drawing a series of connected components
    • each part has a transform matrix
    • each part draws its children relative to itself
      • (torso)
        • head
        • right upper arm
          • right lower arm
            • right hand
        • left upper arm
        • right upper leg
        • left upper leg
  • An interactor tree is a type of scene graph
  • Each component has an affine transformation matrix, and a paint routine
    • Matrix describes the components location relative to its parent
      • ie. what translations should be performed on it
      • The pain routine concatenates the parents affine transformation matrix with the components matrix and then paints using the resulting matrix
      • eg. M1: translate (10,10)
        • M2: translate (5,5)
          • this (5,5) is relative to M1
          • and, supposedly, M1 is relative to its parent as well

As we navigate the interactor tree, we combine successive matrices to reflect the way each component is positioned relative to its parent.

Each component should…

  1. paint itself
    • using its affine transformation matrix
  2. for each of its children
    • save current affine transformation
    • calculate a new transform matrix using the current (parent) transform matrix and the location of the child
      • eg. curr * child_translation_transformation
    • tell child to paint themselves using their new affine transform matrix
    • return the original affine transformation matrix

Inside Tests

We also need to transform any coordinates in events as the events are passed down the interactor tree

  • This allows us to translate between global and local (or relative) coordinate systems

For example, a mouse event in the window’s coordinates will need its coordinates translated to a child component’s local (relative) location prior to passing it down

  • Affine transformations can be used for this, as well

Mouse and shape model must use the same coordinate system. Either

  • Transform mouse to model coordinates
    • suppose we zoomed in… our model coordinates are still the same, but when we click, the window coordinates are no longer in a 1:1 scale with the model’s coordinates
      • if we click (2,2), it may be within a triangle in 2X zoom, but not in 1X zoom
      • to verify if the triangle was actually clicked… need to compare with original coordinates of the triangle
        • if we scale the triangle by 2X (to zoom), we need to 1/2 the mouse coordinates…
        • we need to apply the inverse transformation to the mouse coordinates
  • or Transform model to mouse coordinates
    • alternatively, we can transform the triangle’s coordinates (by a scale, perhaps), and check if the mouse click falls within it…

CS341, 2017-06-19

Undo/Redo

Direct Manipulation Principles

Recall

User should be able to explore without (severe) consequences

  • Reversibility of (almost) all actions helps achieve this

Benefits of Undo

  • Undo lets you recover from errors
    • Input errors (human) and interpretation errors (computer)
    • Allows the user to work quickly (without fear)
      • small mistakes can be undone
  • Undo enables exploratory learning
    • Users mainly learn by trying manipulations of visual objects rather than by reading extensive manuals
    • try things you don’t know the consequence of
    • try alternative solutions
    • removes fear and commitment to decisions
  • Undo lets you evaluate modifications
    • fast do-undo-redo cycle to evaluate last change to document (and see the changes visually)

Checkpointing

  • A manual undo method
    • you can save the current state so you can rollback later
    • eg. a video game
    • eg. source code version control

Undo Design Choices

  • In any undo-redo implementation, we need to consider the following design choices
    • Undoable actions
      • What can’t be/isn’t undone
      • Not all actions need to be (manually) undo-able
        • eg. if you move a character to the right, you don’t “undo” it, you just move back to the left
    • UI State Restoration
      • What part of the UI is restored after undo?
    • Granularity
      • How much should be undone at a time?
    • Scope
      • Is undo/redo global in scope, local, or someplace in between?
      • eg. if several documents are open, undos should be limited to the focused document
  • No single answer, but we have guidelines (above)

Undoable Actions

  • Some actions may be omitted from undo
    • eg. change to selection (just reselect another)
    • eg. window resizing
    • eg. scrollbar positioning
  • Some actions are destructive and not easily undone
    • eg. quitting a program with unsaved data or emptying trash
  • Some actions cannot be undone
    • eg. printing a document

Suggestions

  • All changes to document (ie. the model) should be undoable
  • Changes to the view, or the document’s interface state, should only be undoable if they are extremely tedious or require significant effort
  • Ask for confirmation before performing a destructive action which cannot easily be undone
    • eg. confirm when emptying trash

UI State After Undo

  • What is the user interface state after an undo or redo?
    • eg. highlight text, delete, undo
      • is the text highlighted?
    • eg. select file icon, delete, undo
      • is file icon highlighted?

Suggestions

  • User interface state should be meaningful after undo/redo action is performed
    • change selection to object(s) changed as a result of undo/redo
    • scroll to show selection, if necessary
    • give focus to the control that is hosting the changed state
  • Why? These provide additional undo feedback
    • Show the user something happened

Granularity

  • What defines one undoable “chunk”?
    • chunk is the conceptual change from one document state to another state

Examples

  • MS Word
    • string delimited by any other command
      • bold, mouse click, autocorrect, etc…
  • Sublime
    • token delimited by whitespace
      • a chunk is the entire whitespace-delimited word. When we undo, we remove the chunk, not each individual character

Example: Draw a Line

  • MouseDown to start line
  • MouseDrag to define line path
  • MouseUp to end line
  • MouseDown + MouseDrag + MouseUp = 1 conceptual chunk to “draw line”
    • “undo” should probably undo the entire line, not just a small delta in the mouse position during MouseDrags

Suggestions

  • Ignore intermediate states when under continuous interactive control
    • eg. resizing or moving an object
      • ignore the individual pixels during the drag
  • Chunk all changes resulting from an interface event
    • eg. find and replace all
      • undo will have to undo the entire thing, not just one instance of the word changed
  • Delimit based on discrete input breaks
    • eg. words or sentences in text
    • eg. pauses in typing

Scope

  • Is undo/redo global, local, or someplace in between?

Implementation

Forward v. Reverse Undo

  1. Forward Undo
    • save coplete baseline document state at some past point
    • save change records to transform baseline document into current document state
    • to undo last action, apply all the change records except the last one to the baseline document
  2. Reverse Undo
    • save complete current document state
    • save reverse change records to return to previous state
    • to undo last action, apply last reverse change record
Implementation

Both these options require “change records.” We have multiple ways of implementing these as well

  1. Memento pattern
    • save snapshots of each document state
    • could be complete state or difference from “last” state
    • forward or reverse both just load a new document
  2. Command pattern

Undo Command Pattern

Java Undo

javax.swing.undo.*

  • UndoManager keeps track of undo/redo command stacks
  • UndoableEdit interface is the command to execute (redo) or un-execute (undo)
  • Usually put UndoManager in Model for document context
import javax.swing.undo.*;
public class Model extends Observable {
    private int value = 0;
    private UndoManager undoManager;
    ...

    public void setValue(int v) {
        // create undoable edit
        UndoableEdit ue = new AbstractUndoableEdit() {
            final int old = value;
            final int new = v;
            
            public void redo() {
                value = newValue;
                notifyObservers();
            }

            public void undo() {
                value = oldValue;
                notifyObservers();
            }
        }

        this.undoManager.addEdit(ue); // add edit to manager
        this.value = v;
        notifyObservers();
    }
}

Triggering Undo or Redo

  • Usually done with “undo” and “redo” menu items
    • with key Accelerators for CTRL-Z, CTRL-Y mapping
public void undo() {
    if (undoManager.canUndo())
        undoManager.undo();
}

public void redo() {
    if (undoManager.canRedo())
        undoManager.redo();
}
UndoDemo
  • Model handles all undo actions
    • UndoManager resides in Model
    • setter save UndoableEdits (uses closure)
    • methods added for undo state: canRedo, canUndo

CS349, 2017-06-21

Cut, Paste, Drag-and-Drop

CS350, 2017-05-02

INTRODUCTION

What is an OS?

  • Nowadays, we think about our phone (iOS, Android), Windows laptops, Mac OS, Linux Unity, …
  • Operating systems these days (mostly) have GUIs, are crisp & clean
  • Operating system ==> User experience
    • desktop environment
    • shell
    • interaction
    • not what is happening underneath (today, at least)

An operating system is more than the Desktop or Shell Three views

  • Applcation view
    • What services does the OS provide?
  • System View
    • What problems does the OS solve?
  • Implementation View
    • How is the OS build? (our focus)
I. Application View

The OS provides an execution environment for running programs

  • The execution environment provides a program with the processor time and memory space that it needs to run.
    • creates the environment in which the program will run. Sets the PC counter to start running it
  • The execution environment provides interfaces through which a program can use networks, storage, I/O devices, and other system hardware components.
    • Interfaces provide a simplified, abstract view of hardware to application programs
  • The execution environment isolates running programs from one another and prevents undesireable interactions among them

Operating Systems were simpler back then… for the simple reason that there wasn’t much to do back then. The user would play one game at a time.

  • These days, Chrome itself probably has 14 tabs…
  • NES cartridges were self-bootable. The game didn’t need an operating system to run

Drawbacks: consider the Atari 2600

  • No operating system, hence no APIs for the device
    • this means every game needed to handle the sound, controls, etc. They needed to build the drivers themselves whenever they wanted to build a game
      • this is probably why it didn’t have many games. Or, games didn’t work properly
II. System View

The OS manages the hardware resources of a computer system

  • Resources include processors, memory, disks and other storage devices, network interfaces, I/O devices like keyboards, etc …
  • CPU power and memory are limited, but must be distributed/allocated among running programs. The OS controls the sharing of resources.
    • makes sure no program takes more than it should
  • The OS iteself uses resources, which it must share with application programs
III. Implementation View of an OS

The OS is a concurrent, real-time program

  • Concurrency arises naturally in an OS when it supports concurrent applications, and because it must interact directly with the hardware
  • Hardware interactions also impose timing constraints
    • OS needs some kind of library to share these resources
      • a printer, for example, can only print one item at a time. We need some software means to ensure current jobs aren’t interrupted

What an OS does…

  • Virtualizes and abstracts resources
    • don’t want the program to interact with the graphics card directly. As such, the operating system needs an interface to allow interation (abstracted)
      • don’t want to set the frames and update displays yourself. The OS provides functions in the form of draw(..) to abstract this
  • Creates execution environments for applications
  • Provides persistence: manages data that exists after shutdown

The OS and the Kernel…

  • used to be called the Master Control Proram (MCP)
  • kernel
    • the operating system kernel is the part that responds to system calls, interrupts, and exceptions
  • operating system
    • includes the kernel, and may include other related programs that provide services for applications
      • utility programs (like scans)
      • command interpreters (like shells)
      • programming libraries (like C libraries, drivers, APIs)
    • started out as just I/O libraries. These were common, and made sense to make them reuseable.
    • then came batch scripts
    • multi-programming: the CPU was idle when memory operations took a while. Naturally, it made sense to figure out how to use the CPU during this downtime.
    • eventually, concurrency, etc …
OS Abstractions

The execution environment provided by the OS inclues a variety of abstract entities that can be manipulated by a running program.

  • files and file systems
    • abstract view of secondary storage
  • address spaces
    • abstract view of primary memory. Extension: virtual memory
  • processes and threads
    • abstract view of program execution
  • sockets and pipes
    • abstract view of network or other message channels. The user doesn’t have to worry about passing bytes and some such.

Course Topics

  1. Introduction
  2. Threads & Concurrency
  3. Synchronization
    • protect data that is being used by different threads
  4. Processes and the Kernel
  5. Virtual memory
  6. Scheduling
    • make sure programs are distributed the necessary resources in an optimal way
  7. Devices and Device Management
    • harddrives, SSDs, etc
  8. File systems
  9. Interprocess Communication and Networking

Notes for future reference

Try not to use printf(…). GDB

CS350, 2017-05-04

THREADS AND CONCURRENCY

Threads provide a way for programmers to express concurrency in a program

Note:

  • Scheduling can encounter different delays, so don’t expect threads to go in any particular order
  • printf forces threads to run in a particular order, thus hiding different problems that can occur in scheduling

OS/161 Threaded Concurrency Examples

  • A thread can create new threads using thread_fork
  • New threads start execution in a function specified as a parameter to thread_fork
  • The original thread which called thread_fork and the new thread proceed concurrently, as two simultaneous sequential threads of execution
  • All threads share access to the program’s global variables and heap
    • Threads can communicate with each other throw global variables/flags. This lets you control the flow by halting a certain thread until a flag is set to true
    • Threads do not share stacks (more info later)
  • Each thread’s function activations are private to that thread

Prototype for thread_fork

int thread_fork(
    const char *name, // name of new thread, used for debugging
    struct proc *proc, // NULL for now to make this thread part of the existing program
    void (* func) // entry point: new thread's function
        (void *, unsigned long),
    void *data1, // function's first param
    unsigned long data2 // function's second param
);
  • See kern/include/thread.h
  • terminate the calling thread using void thread_exit(void);
    • not relevant for OS/161, but other libraries’ thread_exit returns a status code to the parent. Can just return
  • voluntarily yield exectuion using void thread_yield(void);
    • thread_yield enabled co-operative concurrency. Programs that didn’t call thread_yield didn’t have concurrency, because only that thread would be running

Why Threads?

  1. Parallelism exposed by threads enables parallel execution if the underlying hardware supports it
    • programs can run faster
  2. Parallelism exposed by threads enables better processor utilization
    • if one thread has to block, another may be able to run

The Stack

When using multiple threads, need to pay attention to the stack frame of each operation

If I have multiple threads in the same program, they’re going to share an address space. They don’t get their own copy of the data. Their stack, however, is going to be unique

  • the local variable values for each thread is particular to that thread
    • we can’t do this without unique stacks
    • Question: why not just use the entire stack for every thread?
      • how to keep track with each thread’s specific frames?
      • The idea of a stack is to be able to push and pop without having to worry about order. If all the threads’ frames are interleaved, we can’t do that.
  • conceptually, each thread executes sequentially using its private register contents and stack
  • Each thread also keeps its own copy of the program counter
  • Each thread has its own stack pointer (for obvious reasons)
  • When we start running a new thread, we need to save the old thread’s state(s)

Debugging OS/161

Need to connect OS/161 to compiler. NEED 2 CONNECTION INSTANCES TO SEE THE DEBUG

  • sys161 -w
    • -w : wait for a connection with debugger before proceeding
    • The debugger connection will be init’d in another terminal instance
  • cs350-gdb kernel-ASST0
    • initialize debugger connection using assignment 0
    • dir ../os161-1.99/kern/compile/ASST0 into (gdb)
  • need to set some breakpoints first
  • note: see stack: enter bt into (gdb). This will show the backtrace
  • note: see values of variables at a breakpoint: enter print curthread into (gdb) to show the value of curthread. It may initially show the pointer address of curthread, but you can use pointer arithmetic to get the actual value. Example: print *curthread

CS350, 2017-05-09

Some History

EXEC I 1962 - UNIVAC 1107

  • A batch processor with multiprogramming
    • Automatically loads the next job upon completion of another
    • Do not wait (i.e. let CPU idle) for I/O to complete. Save A’s state, start running B’s I/O
    • 288 KB of memory

Implementing Concurrent Threads

Options

  1. Multiple processors, multiple cores, hardware multithreading per core
    • P processors, C cores per processor, M multithreading degree(s) per core
      • ==> P*C*M threads can execute simultaneously
    • From an operating systems perspective, option 1 is boring.
  2. Timesharing
    • Multiple threads take turns on the same hardware
    • Rapidly switch from thread to thread so that all can make progress

In practice, both techniques can be/are combined

Notes

  • Threads don’t always terminate.
    • e.g. repeating a movie over and over will cause these threads to keep running. Theoretically this will hijack your processing power
    • Through timesharing, other threads can have an opportunity to run
Timesharing and Context Switches

When timesharing, the switch from one thread to another is called a context switch What happens during a context switch?

  • Decide which thread will run next (scheduling)
  • Save register contents of current thread
  • Load register contents of next thread

Thread context must be saved/restored carefully, since thread execution continuously changes the context

  • Sometimes, threads have higher priority. Naturally, there should be some way to determine which thread(s) require more processing time.
    • OS/161 is round robin (no priority)
Context Switch on the MIPS

Saving registers of old thread

/* See kern/arch/mips/thread/switch.S */

switchframe_switch:
    ; a0: address of switchframe pointer of old thread
    ; a1: address of switchframe pointer of new thread

    ; Allocate stack spac efor saving 10 registers
    addi sp, sp, -40
    sw ra, 36(sp)
    sw gp, 32(sp)
    sw s8, 28(sp)
    sw s6, 00(sp)
    sw s5, 00(sp)
    sw s4, 00(sp)
    sw s3, 00(sp)
    sw s2, 00(sp)
    sw s1, 00(sp)
    sw s0, 00(sp) ; these are the callee-save registers

Loading registers of new thread

; Let the new stack pointer from the new thread

lw sp, 0(a1)
nop ; delay slot for load

; Now, restore registers
lw ...
lw ...
.
.
.
nop ; delay slot for load

j ra ; return. There is a delay slot after jumps
addi sp, sp, 40 ; in delay slot
.end swithframe_switch
What Causes Context Switches?
  1. running thread calls thread_yield
    • the current thread is voluntarily giving up the CPU and letting another thread go
  2. running thread calls thread_exit
    • the current thread is gone and deleted from the system. Thus, need a new thread to run
  3. running thread blocks, via a call to wchan_sleep
    • more on this later …
    • e.g. hardware like printers require an innate delay/sleep between print processes. If a thread goes to sleep while waiting for resources, we can switch to another thread to run
  4. running thread is preempted
    • the current thread involuntarily stop running
Preemption
  • WIthout preemption, a running thread could potentially run forever, without yielding/blocking/exiting
    • the OS can’t just stop it for no reason
    • This is done using hardware interrupts (like key-presses)
  • Preemption means forcing a running thread to stop running, so that another thread can have a chance
  • When an interrupt occurs, the hardware automatically transfers control to a fixed location in memory
    • When an interrupt is received, the CPU keeps the address of a trap frame. The CPU will immediately execute the code at the trap frame. This code will save the context of the thread that is to be interrupted
    • Since we’re interrupting, the thread could have been executing anything. Thus, we have to save everything (not just callee-save registers).
      • e.g. registers like hi or lo
  • At that memory location, the thread library places a procedure called an interrupt handler
  • The interrupt handler normally:
    1. create a trap frame to record thread context at the time of the interrupt
    2. determines which device caused the interrupt and performs device-specific processing
    3. Interprets how long the thread had been operating. If this time exceeds the quantum, the OS will call thread_yield and force a context switch
OS/161 Thread Stack After an Intercept [19]
  1. Add a trap frame
  2. Interrupt handling
Preemptive Scheduling
  • A preemptive scheduler imposes a limit, called the scheduling quantum on how long a thread can run before being preempted
    • If the thread exits or finishes before this time limit, everything is good
    • Every x units of time, the CPU fires an interrupt. This is a shorter cycle than the quantum.
      • This is how the CPU keeps track of how long threads have been running. This is also how the CPU determines a thread is complete
    • Suppose a thread exits 2ms into a 20ms cycle. We need to select a new thread, which will run for 38ms.
  • The quantum is an upper bound on the amount of time that a thread can run. It may block or yield before its quantum has expired
  • Periodic timer interrupts allow running time to be tracked.
  • If a thread has run too long, the timer interrupt handler preempts the thread by calling thread_yield
  • The preempted thread changes state from running to ready, and is placed on the ready queue
OS/161 Thread Stack After Preemption
  • The thread is running happily. Then, there is an interrupt. So, we immediately call the trap frame.
  • Then, we let the interrupt handler (some specific handler depending on when/why the thread was interrupted) do its business.
  • The thread is yielded, and then the CPU switches to a new thread.
  • There needs to be a balance between the quantum and how much work is actually done in a thread. We don’t want to interrupt a thread so often that hardly any work gets done.
    • This will be especially bad if the interrupt handling and thread switching does more work than the thread itself.

CS350, 2017-05-11

Prof Email: lanortha@uwaterloo.ca

twothreads problem

  • Suppose there are two threads in a system
  • Round robin scheduling
  • Scheduling quantum: Q ms
  • Single processor
for i from 1 to N do
    compute for C ms
    sleep for S ms
end

Note: To solve these thread problems, try to envision the flow.

  1. First, assume that C < S and C < Q. Suppose both threads start at time t=0. At what time will both threads be finished?
    • Draw the cycle
       XXXYYYY|XXXYYYY| ... |XXXYYYY|
       XXXY|YYYXXXY| ... |   XXXY|YYY
      
      • Here, we have (C+S)N + S, with S extra ms at the end
  2. Second, assume that S < C < quantum
    • Again, the quantum has no effect
       XXXXXX|YYYZZZ|XXXXXX|YYYZZZ| ... |YYY   |
          |XXXXXX|YYYZZZ|XXXXXX| ... |XXXXXX|YYY
      
    • X = computer, Y = sleep, Z = extra wait
      • Here, we have 2NC + S

Two-Thread Example (P1) [slide 27]

Synchronization

Key concepts

Critical sections, mutual exclusion, test-and-set, spinlocks, blocking and blocking locks, semaphores, condition variables, deadlocks

We use multi-threading to actually have threads work together to achieve some goal. Since all threads share the address space and global data (everything but the stack), we need to make sure these threads don’t fuck up the shared varialbes by using it at the wrong time.

  • Suppose int x = 0;
    • How do we have multiple threads reading and writing the same variable at the same time? What will happen?
      • What if thread2 uses x while it is in the middle of being changed?
      • How can we know thread2 is using the right x value?
  • If one thread calls add() on a x and another calls sub() on x at the same time, we couldn’t possily know what the result will be.
  • To analyze this, we need to understand what operations like x++ and x-- actually do
    • In MIPS, when we do x++, we have at least 3 operations. Load the value. Update it. Save the value
      • This can be interrupted at any point by another thread using x
  • Critical Section Examples [slides 5,6,7]
    • We have no control over where, exactly, thread1’s MIPs operation is interrupted.
    • We know our context switches saves the register values without problem.
    • Sometimes, thread2’s operations are pointless because thread1 hadn’t had a chance to save its computed value yet
    • Note that no two operations can use the same address at the same time. Inevitably, one thread’s operation will run before the other.

When the result depends on the exact order in which our methods are called, we have a race condition

  • Not really what we want. When we do add() and sub() we know exactly what the result should be. However, we can’t ever be sure.

Solution Force certain sections of the code to execute in a particular order. By doing this, we avoid having multiple threads trying to read/write to the same variable at the same time.

Volatile

If a variable is volatile, the compiler will be forced to load and store the value on every use.

  • Recall in assembly optimization, sometimes we take a shortcut and avoid calling lw and sw when we don’t really need to.
    • Sometimes we store commonly used variables in a register
    • Other times, we might realize that we call lw even though we did that from another operation

Another Critical Section Example [slide 9]

  1. list *lp has one item
  2. T1 and T2 call list_remove_front
  3. Suppose T1 sees that lp is not empty. It reaches element=lp->first but doesn’t call it (yet).
  4. We have a context switch to T2
  5. T2 finishes list_remove_front. It sets num_in_list to 0, and sets list->first=NULL.
  6. T1 starts running again. But now, list->front is NULL. Segmentation fault
  • If two threads call list_remove_front, one of them should remove the front, and the other should not crash. It should just do nothing.
  • This is not the only race condition (not even close)

More Critical Section Example [slide 10]

We are appending to the end of the list.

  1. Suppose our list is empty
  2. T1 and T2 call list_append
  3. T1 sets element->item = new_item (== 1) and the assertion succeeds.
  4. T1 checks is_empty(lp), which is true, but doesn’t run the condition block (yet)
  5. T2 runs. It sets element-> = new_item (== 2)
  6. T2 adds the new element and increments lp->num_in_list
  7. T1 runs, again. However, it’s inside the is_empty(lp) block. After T2, lp is not empty.
  8. T1 sets lp->first = element. This element was created by T1.
  9. Problem: T2 created an element using malloc, but it was overwritten by T1.
    • This is a memory leak
    • Moreover, it’s like T2 didn’t do anything to the array

Note: when using dynamic array in assignments, pay attention to this

Mutual Exclusion

To prevent race conditions, we can enforce mutual exclusion on critical sections in the code

  • One, and only one thread is in these critical section(s) at a time
    • example: only one person in a bathroom stall at a time. The stall is a critical section
      • If you’re the one that locked the bathroom stall door, you should be the only one that can unlock the door.
      • If someone else can unlock the door from the outside, we still have a race condition
  • How do we have a locking door around our critical section?
    • Simplest version: a global variable lock=true. If it’s false, we can’t use the section
      • Before we use the critical section, we Acquire(&lock)
      • After, we Release(&lock)

Example

bool v, lock=false;

Acquire(bool *lock) {
    while(*lock) {}; // keep trying while someone else has the lock 
    // finally false, the door opens

    *lock=true;
}
  • Does this work? No. Why? Look ahead to how we can fix it

CS350, 2017-05-16

cont’d from last class

We try to avoid race conditions. To do this, we need some sort of synchronization.

To protect critical sections, we use locks. Previously, we stated that C code doesn’t work for building Acquire.

  • If lock is initially available, and two threads try to acquire it
    • T1 starts, reaches the while(*lock) line, and exits the loop
    • We have a context switch
    • T2 starts, and exits the while(*lock) loop. It sees *lock=true and finishes
    • T1 resumes, and sets *lock=true and enters the critical section
  • Can we fix this with C code? Doesn’t look like it
  • We need a hardware-level function. An atomic instruction that cannot be broken into smaller piece
    • Means we will not have an interupting between the test (loop) and set (=true) operations.
    • x86 has an instruction called xchg $src, addr
      • puts the src/value of $src into $addr
      • the old value of $addr will be put into $src
xchg(value, addr) {
    old = *addr;
    *addr = value;
    return old;
}
  • xchg is, effectively, an atomic test and set. If the lock is not available (i.e. lock==false), it will set it to true and return false (and exit loop). If the lock is not available, xchg returns true and keeps spinning
    • see slide 18 to see in-line assembly in C
    • this course will not ask you to do it…
Acquire using xchg
Acquire(bool *lock) {
    while(xchg(true, lock));
}

SPARC

Side note, SPARC was the first 64-bit architecture. SPARC 64 SLFX has 34 cores and was released last year.

  • 32 cores are for general purpose
  • 2 of them are reserved for utility and the operating system
    • This means you can have a very responsive operating system
  • Its atomic instruction is called cas
compareAndSwap(addr, expectedValue, newValue) {
    old = *addr;
    if (old == expectedValue) // has the value changed since I last checked?
        *addr = newValue;
    return old;
}
  • suppose *addr=15, expectedValue=12, newValue=3
    • *addr != expectedValue, so no change and return 15
    • For our purpose, suppose expectedValue=false. This is the only case when we should change the lock
Acquire using cas
Acquire(bool *lock) {
    while(cas(lock, false, true));
}

Spinlocks in OS/161

In our lock implementation, we shouldn’t be accessing the assembly (for our assignment)

Spinlocks spin on the CPU until our desired state is reached and a lock can be acquired

  • This seems like an obvious issue. spinlocks are using the CPU to do nothing important. There’s no workaround, they have to do this to achieve what they do. Still, we can improve it.
  • OS/161 spinlocks are implemented already
    • see semaphore implementation
    • there is an init, acquire, and release function provided

Using Load-Linked / Store-Conditional [18]

MIPS does not have an atomic instruction. It uses two instructions to achieve what we want.

  • x is the old value in the addr sd
  • y=1 (want to set lock and acquire it, if possible)
  • if (x == value in sd)
    • If values are the same, we will set *sd=y and then set y=success
    • Else, y=failure
  • There are 3 outcomes for this code
    • Load-linked is going to get the old value of the lock.
    • If no code has changed the value of the lock, and the lock is true. Then x == value in sd, is true and we return success.
    • If no code has changed the value of the lock, and the lock is false, we’ll take the lock and return success.
      • Hence, we need to check if y==failure. If true, return 1 and tell the while loop to keep spinning
        • Something else is using the lock
      • If y=failure, we don’t return 0. The lock could be false and didn’t change!
        • Here, return x which is the value at the lock before we took it.
          • If the lock was true and we took it, we’ll return x=true=1.
          • If the lock was false, and we took it, we’ll return x=false=0 and we stop spinning
          • Double check this part

Ideally, if a lock is still spinning, we want it to sleep (not hog to CPU) A lock, in this case, is just called a lock.

  • Inside of lock_acquire, if we are unsuccessful, the lock is blocked and goes to sleep
    • For various reasons, a thread might need to wait for something
      • Wait for a lock to be released by another thread
      • Wait for data from a slow(er) device
      • Wait for input from a keyboard
      • Wait for busy device to become idle (like a printer)
    • When writing computationally heavy code, and we don’t call yield, our CPU can begin to overheat.
      • It would help to send threads on vacation. The developer can put blocks in code to put threads to sleep to let the CPU cool down
    • When a thread blocks, it stops running.
      • The scheduler chooses a new thread to run
      • A context switch occurs: from the blocking thread to the new thread
      • The blocking thread is queued

Wait Channels in OS/161

We do not have a master “blocked queue”. All the threads that are sleeping are waiting for something different, as mentioned above.

We will create a wait channel for every single thing a thread could be waiting on. If we have a lock (resource), it will have a wait channel.

  • Wait Channels are just queues. When we call sleep, we put the thread onto the queue.
    • wchan_sleep(..): currThread goes to sleep and puts it onto the wait channel specified
    • Thread goes to “blocked”
  • We can wake one, or all of the threads
    • wchan_wakeone/all(..): currThread goes to ready and master queue(?)
  • We also have wchan_lock(..)
    • prevents operations on wait channel wc

CS350, 2017-05-18

Running a lock test: `synchtest.c`

* $ sys161 kernel-ASST1 "sy2;q"
    - also `uw1`

SEMAPHORES

Consider a room. It has 73 seats (resources). Suppose students are threads. When they come in the room, they look for empty seats and sit down. If no available seat, then the thread must wait.

A semaphore helps keep track of which resources are available. Similar to a lock, but instead of a held/unheld, it keeps a counter of the # of resources available

  • A semaphore is a synchronization primitive that can be used to enforce mutual exclusion requirements.
  • Can be used to solve other kinds of synchronization problems
  • A semaphore is an object that has an integer value, and that supports two operations
    • P: if the semaphore value > 0, decrement the value. Otherwise, wait until the value is greater than 0 and then decrement it
      • take a resource
      • “P the semaphore”: __p__assering: passing
      • if the semaphore value is 0, block(?)
    • V: increment the value of the semaphore
      • return a resource
        • “V the semaphore”: __v__rijigave: release
    • By definition, operations P and V are atomic
  • Not necessarily about a critical section, but rather protecting a resource
    • Note, semaphores don’t care who returns a resource
  • Binary semaphore
    • initial_value = 1, only one resource available
    • effectively a lock
      • except someone else can V the semaphore (no ownership)
  • Counting semaphore
    • initial_value >= 0
    • can start at 0, waiting for another thread to release resources
Producer/Consumer Synchronization with Bounded Buffer
  • Suppose we have threads (producers) that add items to a buffer and threads (consumers) that remove items from the buffer
    • Subaru production plant in Indianapolis (producer). Creates cars and puts it in the parking lot (the buffer)
    • What if the parking lot (buffer) is full?
    • What if a consumer all the way from Vancouver comes to Indianapolis to pick up cars?
  • Suppose we want to ensure that consumers do not consume if the buffer is empty. Instead they must wait until the buffer has something in it
    • If the parking lot is empty, don’t send a truck from Vancouver to pick up items from the buffer
  • Similarly, suppose the buffer has a finite capacity (N), and we need to ensure that producers must wait if the buffer is full
    • Subaru plant should not build more cars if their parking lot is already full

This requires synchronization between consumers and producers

  • Semaphores can provide the necessary sync.
    • note, semaphores do not have a “get” function to check # of available resources
  • Need 2 semaphores for 2 different types of resources
    • consumer’s resources are “non-empty spots”
    • producer’s resources are “empty spots”
struct semaphore *Items, *Spaces
Items = sem_create(...) // initially 0
Spaces = sem_create(...) // initially N

Producer's pseudo-code:
    P(Spaces)
    Add items to buffer
    V(Items)

Consumer's pseudo-code:
    P(Items)
    Remove items to buffer
    V(Items)

Problem

  • Buffer is a global shared variable
    • Semaphore does not offer mutual exclusion when used in the way above. Above, it just keeps track of the items available
    • Can have multiple producers adding to the buffer at the same time
      • Need to protect the “add items” in a critical section

A barrier semaphore

  • Semaphore whose initial value is 0. P the semaphore however many times for # of threads forked, and each thread will V the semaphore when it’s done
    • This forces the parent thread to wait until all threads are completed

CONDITION VARIABLES

Another synchronization primitive

  • Each condition variable is intended to work together with a lock
    • use lock to access a critical section
    • but, inside the section, need to wait for a condition variable to be true
      • are we just going to spin until some variable, say, x=5? This costs CPU bandwidth
      • the thread that may set x=5 will/might need to make the update using the same lock you’re currently occupying
  • Condition variables are only used from within the critical section that is protected by the lock
  • Say we have a bottle of beer
    • if beer in mug, drink
    • if no beer, hand is still on the mug, but while you’re holding onto the beer, the bartender can’t fill it up
      • if no beer, take hand off cup (release lock) and let bartender take cup (acquire lock)
      • bartender fills it, releases lock, gives beer back, wakes you up, you acquire lock again
  • Three operations are possible on a condition variable
    • If we’re in a critical section, and we realize a variable is not the way we want it, we call cv_wait
      • it relinquishes your hold on the critical section, and thread goes to sleep
      • lock is released as well
      • Once the thread is unblocked, it reacquires the lock
    • Once a variable has been updated, call cv_signal to wake one thread waiting on this condition variable
    • cv_broadcast is similar, but unblocks all threads that are blocked on the condition variable
Using Condition Variables

Condition variables get t heir name because they allow threads to wait for arbitrary conditions to become true inside of a critical section

  • Normally, each condition variable corresponds to a particular condition that is of interest to an application
    • for example, in the bounded buffer producer/consumer problem. Two conditions are
      • count > 0 // there are items in the buffer
      • count < N // there is free space in the buffer
    • when a condition is not true, a thread can wait on the corresponding condition variable until it becomes true
    • when a thread detects that a condition is true, it uses signal or broadcast to notify any threads that may be waiting
  • Note that signalling (or broadcasting) to a condition variable that has no waiters has no effect. Signals do not accumulate
int volatile count = 0
struct lock *mutex; // for mutual exclusion
struct cv *notfull, *notempty // condition variables

Produce(itemType item) {
    lock_acquire(mutex);
    while (count == N) {
        cv_wait(notfull, mutex); // wait until buffer is not full
    }
    add item to buffer // list_append()
    count++
    cv_signal(notempty, mutex)
    lock_release(mutex)
}
itemType Consume() {
    lock_acquire(mutex)
    while (count == 0) {
        cv_wait(notempty, mutex) // wait until buffer is not empty
    }
    remove item // list_remove_front()
    count--
    cv_signal(notfull, mutex) // signal other threads that need notfull=true
    lock_release(mutex)
    return(item)
}
Waiting on Condition Variables
  • When a blocked thread is unblocked (by signal or broadcast), it reacquires the lock before returning from the wait call
  • A thread is in the critical section when it calls wait, and it will be in the critical section when wait returns
    • However, in between the call and the return, when the caller is blocked, th caller is out of the critical section, and the other thread may enter
  • In particular, the thread that calls signal (or broadcast) to wake up the waiting thread will itself be in the critical section when it signals.
    • the waiting thread will have to wait (at least) until the signaller releases the lock before it can unblock and return from the wait call

If you are a thread that is to make the condition true, you need a lock to protect your access to the shared variable

  • at the point you call cv_signal, you want to guarentee the condition is still true. That some fucker hasn’t changed it between then and now
  • must be the owner of the lock to signal or broadcast
cv_wait(cv *cv, lock *lock)
    wchan_lock(cv->wc)
    // cv needs own wait channel. Need to keep track of threads waiting on this condition
    lock_release(lock) // release hold on critical section
    // someone else needs access to the critical section to make it true
    wchan_sleep(cv->wc)
    --> on a signal or broadcast, code resumes here
    lock_acquire(lock)
    // we're working with the critical section again, need to acquire lock
Monitors

Next most similar thing to condition variables

  • MESA
    • The condition variables that we described in our notes
    • Inside cv_signal, check if_owner_of_lock, wchan_wakeone(cv->wchan)
  • HOARE
    • Inside cv_signal, instead of waking up the thread and let you release the lock, and then let another thread reacquire the lock…
    • Signal thread and then you block. The other thread starts running again

CS350, 2017-05-25

Condition variable test: synchtest.c, line 61, sy3

Incrementing # of CPUs

  • don’t exceed 32 CPUs. Use 8 or 16
  • By increasing the # of CPUs, you increase the probability of encountering sycnhronization issues
Assignment 1 hints

Traffic light: synchronize cars going through an intersection, and ensure no accidents

  • Solve sync problem using locks and control variables
  • Cars can go N->S, E->W, and make L/R turns
    • When you come up to an intersection, theres >1 car going through at once. Instead of just letting one car through N->S, we want cars going S->N to also go through

Hints

  • Best solutions? 4 CVs and 1 Lock
  • Also possible to use 3 CVs and 1 Lock
    • Consider the rules
      • If a car is going N->S, what are the other possible cases of cars going through the intersection? Definitely not E->W or W->S
  • Don’t worry about fairness
    • If first solution works, fuck it. Move on
    • If not, …
      • Real traffic lights work in a few different ways. Some lights operate on timers, regardless of the number of cars waiting at the light. Don’t use timers, but check out an alternate approach
      • Suppose cars are going N->S. If no cars are going E->W, no point switching light. If a car shows up and is waiting for the light to switch
        • Could wait for the intersection empty, then switch
        • Or recognize a waiting car, and let at most N more cars, then switch
          • Set a “pressure plate” to check number of cars going thru
        • cv_broadcast wakes up every thread
          • if you wake up 5 threads but then need to sleep 95 others because you woke 100, is that worth?
  • Common approach: 1 CV for each direction of origin
    • There are other possible reasons for each CV…
  • There is a dynamic array implementation in array.h
  • Don’t worry about # of lanes. If cars go N->S at the same time, they’ll call entry() at slightly different times anyways.
  • See Piazza about # of iterations and tests to test with
  • Don’t do extra work

Deadlocks

The programmer is responsible for discovering and handling race conditions, and figuring our which synchronization primitives are needed.

  • Suppose there are two threads and two locks, lockA, lockB, both initially unlocked
  • Suppose the following sequence of events occur
    • Thread 1 acquires lockA
    • Thread 2 acquires lockB
    • Thread 1 tries to acquire lockB
    • Thread 2 tries to acquire lockA

Problem(s)

  1. (1) gets lockA
  2. (2) gets lockB
  3. (1) tries to get lockB, goes to sleep waiting for lockB
  4. (2) tries to get lockA, goes to sleep waiting for lockA
  5. This code is permanently stuck, because only (2) can release lockB, but is asleep. Only (1) can release lockA, but is asleep.

Two Techniques for Deadlock Prevention

No Hold and Wait
  • Prevent threads from requesting resources if it currently has a resource(s) allocated to it.
  • A thread may hold several resources, but to do so it must make a single request for all of them
  • Suppose we have multiple resources: critical section, modem, and printer
    • If we have a lock on printer, but cannot acquire a lock on the modem, we must release the lock on printer
    • With that said, we need a new method of acquiring locks: try_acquire
      • returns true if you get the lock
      • returns false if you do not get the lock
        • don’t block
      • must acquire all resources in one call, together
acquire(res0); // regular acquire: you either wait on the first resource, or get it. We don't own any other resources at the moment

while(I don't get all resources) {
    try_acquire(each resource we want)
    if false
        release all held

    // spin in loop trying to acquire **all** resources until we get them
}

This thread is spinning instead of blocking

  • It avoids deadlock, but introduces busy waiting. The loop hogs CPU until all resources are acquired
    • quite simple to implement, and is popular
Resource Ordering

Assign a number/order to resource types, and require that each thread acquire resources in increasing resource type order

  • A thread may make no requests for resources of type <= i if it is holding resources of type i.
  • Just ensure we are acquiring locks in same increasing order

Summary

CS350, 2017-05-30

Processes and System Calls

What is a process?

  • An environment in which an application program runs
  • A process includes virtualized resources that its program can use
    • one (or more) threads
    • virtual memory, used for the program’s code and data
    • other resources
      • e.g. file and socket descriptors
  • From now, programs have one thread
  • A process itself is >1 thread
  • Processes are created and managed by the kernel
  • Each program’s process isolates it from other programs in other processes
    • address space for every program is unique
    • programs/processes cannot talk to each other in direct manners

System Calls

  • System calls are the interface between processes and the kernel
  • A process uses system calls to request OS services
  • Service examples
    • create, destroy, manage processes
      • fork, execv, waitpid, getpid
    • create, destroy, read, write files

System Call Software Stack [L4_S4]

The application makes a call to the Syscall Library (API), which makes a system call to the kernel

  • don’t want user application to communicate with the kernel directly. The application and Syscall library are unprivileged code
  • the kernel is privileged code
    • these are states we put the CPU in. The application is not permitted to communicate with the hardware, like shutting down the computer.
    • Why separate user code from the kernel?
      • Instead of using a nice abstracted library to access the kernel, then developers will try to interface with the hardware better than the kernel
      • So, different applications will have a bunch of different drivers. One of the goals of the kernel is to abstract itself/the hardware for user applications
      • Moreover, different hardware needs different drivers.
      • Additionally, errors like segmentation faults (which means you’re writing to memory outside your address space) would not fire, and you’d end up overwriting memory you do not own.

Kernel Privilege

  • The kernel runs at a higher level of execution privilege than application code
    • privilege levels are implemented by the CPU
  • The kernel’s higher privilege level allows it to do things that the CPU prevents less-privileged applications/programs from doing
    • e.g. application programs cannot modify the page tables that the kernel uses to implement process virtual memories
    • e.g. application programs cannot halt the CPU
    • Something needs to be able to manage these hardware-level settings, processes, data, etc.
  • These restrictions allow the kernel to keep processes isolated from one another—and from the kernel

Application programs cannot directly call kernel functions or access kernel data structures.

How System Calls Work (Part 1)

  • Isolating Application/Syscall Library from Kernel
    • benefits
      • can patch the kernel without affection user applications
    • so how do we do things like save files, which requires privileges?

There are only two things that make kernel code run

  • Interrupts
    • interrupts are generated by devices
    • an interrupt means a device (hardware) needs attention
  • Exceptions
    • exceptions are caused by instruction execution
    • an exception means that a running program need attention
    • e.g. calling an assembly instruction that doesn’t exist
    • e.g. dividing by 0
    • if we want to save a file, we will use exceptions

Interrupts Revisited

  • An interrupt causes the ardware to transfer control to a fixed location in memory, where an interrupt handler is located.
    • the trap frame saves the complete context of the registers, and calls an interrupt handler from the kernel to figure out which interrupt was fired and how to deal with it
    • the trap frame must also switch the CPU from user-mode to kernel-mode (privileged-mode)
    • when restoring the context of the thread later, need to change from kernel-mode to user-mode
      • this is how the kernel gets its execution privilege

Exceptions

  • Condition that occur during the execution of a program instruction
    • e.g. arithmetic overflows, illegal instructions, page faults
  • Detected by the CPU during instruction execution
  • CPU handles exceptions like it handles interrupts
    • control is transferred to a fixed location (trap frame), where an exception handler is located
    • processor is switched to privileged execution mode
  • Exception handler is part of the kernel
MIPS Exception Types [L4_S9]

Note that OS/161 treats exceptions and interrupts the same way.

  • EX_IRQ == 0 is a type of exception that represetns a hardware interrupt.
  • When we want our application to make a kernel call, we fire a system call
    • we need to raise an exception of a “system type”
      • EX_SYS
        • indicates user application wants the kernel to do something

While inside trap frame, need to know what type of exception it was to figure out what to do

  • One of the Exception Types will go into a register
  • The trap frame will call the appropriate handler/dispatcher after reading the exception type

How System Calls Work (Part 2)

  1. To perform a system call, the application program needs to raise an exception to make the kernel execute
    • on the MIPs, EX_SYS is the system call exception
  2. To cause the exception on the MIPS, the application executes a special purpose instruction: syscall
    • other processor instruction sets include similar instructions
      • e.g. syscall on x86
  3. Kernel’s exception handler checks the exception code (set by the CPU when the exception is raised) to distinguish system call exceptions from other types of exceptions

System Call Software Stack (Updated) [L4_S11/S12]

  1. Application makes call to Syscall wrapper library
  2. Syscall Library raises an exception. The exception type is set in a register. The library function performs syscall instruction
  3. The Kernel handles the exception, and returns the value(s) (in a register, perhaps)
    • creates trap frame to save application program state
    • determines that this is a syscall exception
    • determines which syscall is being requested
    • does the work for the requested system call
    • restores the application program state from the trap frame
    • returns from the exception
  4. The Syscall Library function finishes and returns from its call
  5. application continues excecution
li $v0, 1 ; load the system call code
; this code is predetermined
li $a0 ... $a3 ; load the system call params

syscall ; raises exception EX_SYS

Which System Call?

There are many different system calls, but only one syscall exception. How does the kernel know which system call the application is requesting?

  • kern/include/kern
    • application binary interface (ABI)
    • syscall.h
      • contains type codes for different system calls
  • the kernel defines a code for each system call it understands
  • the kernel expects the application to place a code in a specified location before executing the syscall instruction
    • for OS/161 on MIPS, the code goes in register $v0
  • the kernel’s exception handler checks this code to determine which system call has been requested
  • the codes and code location are part of the kernel ABI

Some OS/161 System Call Codes [L4_S14]

System Call Parameters

User and Kernel Stacks

  • Every OS/161 process thread has two stacks, although it only uses one at a time
    • if it only had 1 stack?
      • suppose we’re executing code, and reach an exception
      • there’s no stack for the kernel code to execute
        • We don’t want the kernel to expose its data to the user application by putting its data on the user application stack
  • User Stack
    • used while application code is executing
    • this stack is located in the application’s virtual memory
    • it holds activation records for application functions
    • the kernel creates this stack when it sets up the virtual address memory for the process
  • Kernel Stack
    • used while the thread is executing kernel code, after an exception or interrupt
    • this stack is a kernel structure
    • in OS/161, the t_stack field of the thread structure points to this stack
    • this stack also holds activation records for kernel functions
    • this stack also holds trap frames and switch frames
      • kernel creates them, so it holds them
      • once the exception/interrupt is handled, trap frame restores thread context. It also reverts to the user stack. Then it reverts the CPU to user-privilege

Exception Handling in OS/161

  • First to run is careful assembly code that…
    • saves the application stack pointer
    • switches the stack pointer to point to the thread’s kernel stack
    • carefully saves application state and the address of the instruction that was interrupted in a trap frame on the thread’s kernel stack

Implementing System Calls and Debugging

kern/arch/mips/syscall.c

  • add syscall type handling here
  • tf->tf_epc += 4
    • when receiving syscall, program counter will not advance. So, need to manually increment to jump over the syscall to avoid re-executing it

Debugging

  • continue using -w flag
  • set directory
  • target the unix
  • trace through the system call
    • put a breakpoint at the line where you call something like SYS_open
    • backtracing will show the stack contains only kernel function activations

CS350, 2017-06-01

Multiprocessing

Recall we have a quantum. When it expires, we have a pre-emption, and thus a context switch.

  • The kernel just sees threads. If we have two (single-threaded) processes, we’ll have timer interrupts
    • This interrupt will cause a switch to kernel mode
    • Will check how long the thread’s been running
      • Not long enough? Go back to Process A
    • Keep checking until it exceeds the quantum
  • The kernel looks at the ready pool of threads and chooses another thread to run
    • In this example, Process B starts running
    • When Process B exceeds the quantum, Process A starts running again
Animation Notes
  • Process 1 is running its application. It maintains its application stack frames.
    • close(1)
      • executes like normal, adds a stack frame
    • Makes a syscall: li a0,1 ; li v0,49 ; syscall
      • Starts running common_exception function
        • switches from user mode to privileged mode, and switches to the thread’s kernel stack
        • saves processor state (registers, etc) into a trap frame
        • Now, need to deal with the exception
      • mips_trap(…)
        • Check whether this is an exception, interrupt, or system call
      • syscall(…)
        • Checks the code of the interrupt
        • Turn off interrupts for a little bit. If the exception code is not an interrupt, we turn interrupts back on immediately
          • When a hardware device fires an interrupt, it will keep firing until the CPU acknowledges it has been handled
      • sys_close(…)
  • While kernel is trying to execute sys_close(...)
    • Pre-emption continues even if we are executing kernel code
    • When transferring control to mips_exception, don’t need to switch to privilege-mode, nor switch to kernel stack, because we’ve already done that
    • mips_trap()
    • thread_yield()
    • thread_switch()
    • switch frame
  • Process 2: suppose it had some stuff in its kernel stack already (it was executing before)
    • It executes the code (pops the stack), goes through the trap frame, etc
    • Switch from kernel-mode to user-mode

Suppose the interrupt never happened. We continue off from the first sys_close(...)

  • Handle the sys_close(…)
    • increment PC by 4, etc
  • Return from syscall(...)
  • Return from mips_trap(...)
  • We’re back the trap frame
    • Need to jump back to thread’s application code
    • rfe returns the CPU to unprivileged mode

System Calls for Process Management

  • fork creates a new process
    • does not createa new blank process, but rather an identical clone to the process that called fork
      • user stack is the same
      • values in registers are the same
      • address spaces are the same
    • difference is that when forking, the new process does have a new id number
    • fork returns in both the parent and the child. Their program counter is pointing to the same instruction
    • also, return value of fork is different
      • parent returns process id of new process that was created as a result of calling fork
      • child returns 0
  • execv changes the program that process runs
  • _exit destroys a process. It is called manually
    • terminates the process that calls it
    • process may supply an exit status code when it exits
      • the kernel keeps this return value for future use
  • waitpid synchronizes processes to run in a particular order
    • lets a process wait for another to terminate, and retrieve its exit status code (from _exit)
    • makes sense. Sometimes we want to wait for another process to terminate before proceeding
    • waitpid is equivalent to watching a child
      • when a child dies, the parent will want to know why it died
      • it will block the process until the child dies, and provides the exit status
  • getpid for attribute management
Some Code: fork, _exit, getpid, and waitpid
main() {
    rc=fork(); // returns 0 to child, pid to parent
    if (rc==0) { // child executes this code
        my_pid = getpid();
        x = child_code();
        _exit(x);
    } else { // parent executes this code
        child_pid = rc; // if we're in the parent code, rc is the child\_pid
        parent_pid = getpid();
        parent_code();
        p = waitpid(child\_pid, &child\_exit, 0);
        if (WIFEXITED(child_exit))
            printf("child exit status was %d\n", WEXITSTATS(child_exit));
    }
}

All fork does is create a clone of the existing process

  • If we want to open a program from a shell, we can’t just fork the shell…
  • In order to set what program the process should run, you need to use execv
    • When we call execv, we need to change the process’ address space. Clear out the stack, etc
    • Open the binary file
    • Create a new address space and new block of memory that is appropriate for the new program
      • With a new program, it starts executing at the entry point
    • id of the process does not change
    • user of the process does not change
Some code: execv
int main() {
    int rc=0;
    char *args[4]; // array of strings

    args[0] = (char *) "/testbin/argtest";
    args[1] = (char *) "first";
    args[2] = (char *) "second";
    args[3] = 0;

    rc = execv("/testbin/argtest", args);

    // if execv succeeds, the program that called it is killed
    // it does not return
    // the last thing execv does is jr'ing to the beginning of the execution of the new program
    printf("If you see this, execv failed\n");
    printf("rc = %d errno = %d\n", rc, errno);
    exit(0);
}

Assignment 2a/2b

  • fork, waitpid, _exit in 2a
  • execv in 2b

CS350, 2017-06-06

Assignment 2A Hints

System calls

  • pid_t fork(void)
    • create a copy of the current process. Return 0 for child process, and the PID of the child process for the parent
    • many of the marks for 2A
    • create new process that is an identical clone of the process
    • When the two processes keep running, they can fork into different directions depending on the returned value (whether they’re a child or parent)
  • pid_t waitpid(pid_t pid, int *status, int options)
    • Waits for the process specified by pid. Status stores an encoding of the exit status and the exit code
    • Returns the PID of the process on success, or -1 on error (it can also return 0 if the option WNOHANG is specified and process PID…)
  • pid_t getpid(void)
    • returns the PID of the current process
    • does not need to be implemented right away
fork
  1. A process is really just a data structure that holds some information about the program running/to be run
    • Use proc_create_runprogram(...) to create the process structure
      • set up the VFS (file system) and console
      • found in kern/proc/proc.c
    • Don’t forget to check for errors
      • e.g. what happens if proc_create_runprogram returns NULL?
        • Not enough memory, other issues with memory, etc
        • At every stage, we must check for an error. If we receive an error, need to return an error code
          • These error codes can be found in kern/include/errno.h
  2. Create a new process structure for child process
    • empty to start with
    • Child process must be identical to the parent process
    • as_copy() creates a new address space, and copies the pages from the old address space to the new one
  3. Create and copy address space (and data) from parent to child
    • Address space is not associated with the new process yet
      • look at curproc_setas to figure out how to give a process an address space
        • don’t need to manually malloc and copy over
        • found in kern/proc/proc.c
        • note, you’re not setting the address space of the current process, but rather the child process. See the implementation to see how to do update the address space of a different process
        • again, when encountering any error, need to return an error code
    • related functions can be found in include/addrspace.h
  4. Attach the newly created address space to the child process structure
    • set the pointers properly using the helper functions
  5. Assign PID to child process and create the parent/child relationship
    • How we do this is up to us
    • PIDs should be unique (no two processes should have the same PID)
    • PIDs should be reuseable
      • When can we reuse a PID?
      • This is partially dependent on your implementation. We’ll talk more about this whn we look at _exit and waitpid
        • Also, in the future, need to create a parent-child relationship between two processes
          • maybe every parent keeps a list of its child processes (as pointers)
          • or a list of children PIDs which can be used as keys in a master table
      • Remember that you need to provide mutual exclusion for any global structure!
    • Need to look up a process in a process table later
      • Implementation of the table is up to us
  6. Create thread for child process
    • need a safe way to pass the trapframe to the child thread
    • Now that we have a process, with an address space, with a PID, and a parent-child relationship, need to create a thread
    • thread_fork(...) has two params
      • the second takes a child process
      • entry point function? Take trap frame from parent and put it on the child thread kernel stack
        • pass it in some way from the parent into the child
        • if we look at the entry function prototype, it takes a void param. Can pass trapframe through there
        • if we pass pointer directly into the child, need to use synchronization
        • if we don’t want to use synchronization, need to copy trapframe onto heap and pass the heap pointer to child
      • user stack is already prepared. We’re setting up the kernel stack
        • When entry point for the new thread is running, will be in kernel mode
        • Copy data into a local variable and will be automatically in the kernel stack for the thread, because when the entry point starts running, it is running in kernel mode
      • using local trapframe variable, need to set register $a3 to be appropriate return values
      • also need to increment PC by 4
        • this is another local variable
      • Do not modify the trapframe until we attach it to the child process, so do it in the entry point function
  7. Child thread needs to put the trapframe onto the stack and modify it so that it returns the current value (and executes the next instruction)
    • see above step
  8. Call mips_usermode in the child’s thread to go back to user-space
    • the child has no way on its own to go back to user-privilege
    • mips_usermode fakes a return from a syscall. Will return the trapframe and switch to user-mode

OS/161 provides a large number of helper functions

waitpid

Block parent process until child has exited by calling _exit

  • Need to be implemented at the same time as _exit
  • See widefork.c test for usage of waitpid
    • WEXITSTATUS(...) is implemented for us, only need to implement waitpid
  • waitpid can only be called on a child
    • first things to check is if the given PID one of my children
      • if not, return immediately with an error code (see errno.h, or 2A hint)
  1. If waitpid is called before the child process exits, then the parent must wait/block
    • What should it block on? Semaphore? Condition variable in a process table?
    • Condition variable specific to the parent process?
    • To the child process?
    • Use a condition variable. When waidpid is called, call cv_wait on the child process, thus blocking until the child exits
  2. If waitpid is called after the child process has exited, then the parent should immediately get the exit status and exit code
    • the child needs to leave some data as long as its parent is alive
      • cannot lose this information. Need to be saved somewhere
      • suppose your parent is dead
        • do not keep code around. No one will care about your rval anymore
      • suppose a parent dies after all its children
        • can delete the exit codes left behind by its children
        • only time we keep these exit codes is when the parent still exists
  3. PID cleanup should not rely on waitpid
    • parent process is not guaranteed to call waitpid when it exits
  4. Encoding exit status and exit code
    • exit code comes from _exit()
    • In this assignment, exit status should always be _WEXITED
      • take the integer parameter from exit() and combine them
        • use a helper function to do this combination

In _exit(), when a child process dies, it should wake up its parent…

Extras

  • Implement the WNOHANG option
    • if child is still alive, return ECHILD instead of blocking
    • this helps the parent ping the child, checking if it’s still alive
  • Add support for WAIT_ANY (-1 PID)
    • block until first child exits
    • return that child’s PID in the return value
getpid
  • Returns the PID of the current process
  • (see slides from Piazza)
_exit
  • Causes the current process to exit
    • don’t worry about having multiple threads in a process
    • We don’t expose thread_fork as a system call. Therefore, user processes will only have one thread
  • Exit code is passed to the parent process
  • When a child terminates if my parent is waiting on me to exit
    • if yes, need to wake
      • once they wake up, they will return from the waitpid call, get my exit status code, and delete me
    • only need to store the exit code if my parent is alive
Common Problems
  • Whe implementing fork, there tends to be a struggle with putting the trapframe on the kernel stack
    • easy to do, but easy to make a mistake w/ memory (typical C-pointer problems)
  • Deadlock on waitpid and _exit
  • Deadlock on PID table

Virtual Memory

Recall the form of the address space

0x0 | code | Data constants | Heap ---\> <--- Stack |

RAM

OS is going to find some free space in RAM and give it to my program. Suppose our RAM looks like the following

0x0 | | Minecraft | MATLAB | | 16gb

  • Suppose Minecraft used the address space from 0x10005000 to 0x10008000
  • And MATLAB used 0x10008000 to 0xFFD00000
  • If our user program knows exactly where it lives in real memory
    • this is an issue, because by virtue of knowing where I live in memory, I know where other people live in memory
    • I could access other people’s memory using pointer arithmetic
    • It might be ok if Minecraft screws with MATLAB, but we’d have serious issues if Minecraft was touching our operating system’s memory
      • We use virtual memory to make programs think they’re the only program in existence

CS350, 2017-06-08

  • When we use virtual memory addresses, we need to ensure our translations between physical memory and virtual memory addresses to be efficient (and correct)
  • Moreover, we need a kernel that is efficient at distributing physical memory
  • A virtual address space can be smaller than the physical address space

Virtual Addresses

  • The kernel provides a separate, private virtual memory for each process
  • The virtual memory of a process holds the code, data, and stack for the program that is running in that process
  • If virtual addresses are V bits, the maximum size of a virtual memory is 2^v bytes
    • for MIPS, V=32
    • in our slides, V=16
  • Running applications see only virtual addresses
    • program counter and stack pointer hold virtual addresses of the next instruction and stack
    • pointer to variables are virtual addresses
    • jumps/branches refer to virtual addresses
    • even our kernel will run on a virtual address space

Address Translation

  • Each virtual memory is mapped to a different part of physical memory
    • if we want to execute an instruction, and we have its address, we need to find its actual address in physical memory
  • Since virtual memory is not real, when a process tries to access (load or store) a virtual address, the virtual address is translated (mapped) to its corresponding physical address, and the load or store is performed in physical memory
  • Address translation is performed in hardware, using information provided by the kernel
    • the Memory Management Unit (MMU) is a physical device, whose sole job is to take a virtual address and translate it into a physical address
    • the MMU cannot operate on its own
      • the OS needs to give some information. This info depends on the architecture and virtual memory implementation you have

Dynamic Relocation [vm_S7]

Suppose we have some physical memory

  • 0x0 to 0x3ffff
  • When we try to allocate memory for a new process, I will find a chunk of memory that fits the process, and I will claim it
    • I will also assign this chosen memory space for the process
    • perhaps PROCA will occupy 0x0 to 0x6fff
    • and PROB will occupy 0x6fff to …
  • If a process only needs 2KB, that’s all we give it. We don’t necessarily allocate the limit/maximum memory a process could use
  • Static relocation
    • We allocate memory as we go, for however much the process requires
    • Problems
      • Suppose PROC_C occupied 2KB
      • and PROC_E occupied 10KB
      • We free the two, but the two processes had separate locations (non-adjacent) in memory
        • We freed 12KB, but it is fragmented. A 12KB program will not be able to fit, though we’d like it to be able to
  • Dynamic Relocation
    • When we encounter fragmentation, we just shift some processes’ physical address space
    • We keep track of the offset (from 0) and the limit of the process’s memory usage
      • We use offset and limit to do our translation

Address Translation for Dynamic Relocation

  • CPU includes the MMU, with a relocation register and a limit register
    • relocation register holds the physical offset (R) for the running process’ virtual memory
    • limit register holds the size L (limit) of the running process’ virtual memory
if v >= L, then generate exception
else
    p = v + R
  • recall, the virtual address begins at 0 and is limited
  • The kernel maintains a separate R and L for each process, and changes the values in the MMU registers when there is a context switch between processes

Properties of Dynamic Relocation

  • Each virtual address space corresonds to a contiguous range of physical addresses
    • OS is responsible for finding a contiguous walk of memory
    • If a process requires 2GB, we need 2GB of contiguous memory
      • What are the odds of finding 2GB of free memory?
      • Dynamic relocation lets us defragment our memory in order to find this contiguous walk of 2GB
        • Problem is that this defragmentation is rather slow
          • Have to move almost every other process’ address space
  • While dynamic relocation is the easiest, and maybe fasted, it is susceptible to internal fragmentation
    • Solving this is difficult
    • Although it is efficient in how much data is required to implement, and how fast the translation occurs

Example: Process A [vm_S10]

Limit register:      0x0000 7000
Relocation register: 0x0002 4000

v = 0x102C  p = 0x0002 502C
v = 0x8800  p = exception
v = 0x0000  p = 0x0002 4000

Example: Process B [vm_S11]

Limit register:      0x0000 c000
Relocation register: 0x0001 3000

v = 0x102C  p = 0x0001 402C
v = 0x8800  p = 0x0001 B800
v = 0x0000  p = 0x0001 3000
  • Note, theoretically, virtual memory addresses could be the same as physical memory addresses
    • The offset will have to be 0
    • However, since the OS/kernel resides at address 0 in physical memory, this shouldn’t happen

Problem with Dynamic Relocation

  • As mentioned earlier, in order to find a contiguous range, we need to defragment some memory. Finding the memory to defragment is too much work

Potential Solution

  • If we can’t find a contiguous piece of memory, why can’t we just find the different chunks of free memory and put them together?
    • This is tough to manage, but we do have a solution along these lines

Paging: Physical Memory

  • Suppose we have 256KB total physical memory
  • We pick some size, divide the entire physical memory in pieces of this size
    • Suppose we choose a physical page size of 4KB (4096 bytes)
    • We divide 256KB by 4KB, and so we have 64 frames/pages of memory

Note

  • 4KB is 2^12
  • 2^12 is 4096 bytes
  • 4096 is 0x1000

  • If I have a 4KB frame, I should have 4KB pages
  • Each address space, now, will also be divide into some number of pages
  • We won’t have external fragmentation here, but we will have some internal fragmentation
    • If you only need 1KB, you’re going to get 4KB anyways
  • Suppose we need 28KB for a process
    • We traverse our physical memory and find (and use) the first 7 (x4 = 28KB) unoccupied pages
    • We can have pages across memory, and it need not be in order
    • This solves the external fragmentation because we look for pages, which is the same size of the frame. So, we never allocate for anything bigger or smaller that we need(?)
  • With this implementation, we’ve mapped pages of virtual memory to frames of physical memory
    • These frames don’t have to be in RAM
    • Most OS’s only load pages of the address space in RAM that you are actively using
      • Your address space can have some pages in memory, other pages in other devices
        • this is called Demand Paging

Page Tables

  • Knowing page number, you can figure out the address of the frame
  • This table is created and maintained by the operating system
  • Every process has own page table
  • Size of the page table?
    • size = virtual memory size / page size
      • not how much memory, but rather how many entries

Address Translation in the MMU, Using Paging

  • The MMU includes a page table base register which points to the page table for the current process
  • How the MMU translates a virtual address
    • determine the page number and offset of virtual address
      • page number is the virtual address divided by the page size
      • offset is the virtual address modulo the page size
    • looks up the page’s entry (PTE) in the current process page table, using the page number
    • if the PTE is not valid, raise an exception
    • otherwise, combine the page’s frame number from the PTE with the offset to determine the physical address
      • physical address = (frame number * frame size) + offset

See vm_S17 for illustration of Address Translation

page # = v / page size

offset = v % page size
// modulo with hex??
// how many bits does my page # need?
// how many entries in our page table? If we have virtual memory that is
// 64KB, we have 16 pages (maximum)
// How many bits do I need to represent 16? 4 bits
// How many bits do I chop off for the modulo?

// how many bits for pg#? log(size(PTE));
// if PTE=16, then bits for pg#=4
// take virtual address and the highest order 4 bits are the pg#. The rest are the offset
// this is easier to apply to hex than actually modulo'ing hex

// assuming PTE lookup was valid
physical address = (frame # * frame size) + offset
  • The OS for OS/161 determines the stack size for processes
    • Modern OS’s have more flexibility but OS/161 just uses this simplification

CS350, 2017-06-13

Midterm Coverage

Beginning of the course to slide 40 of virtual memory

Recall

  1. p-bit addresses -> 2^p bytes
  2. we divide physical memory into frames
  3. and divide virtual memory into pages
  4. page size == frame size

Questions

How many pages are there, or what is the size of the page table

  • given an amount of virtual memory, how many pages fit into it?
    • v.mem size = 2^v bytes
    • pg. size = 2^m bytes
    • of pages = size of page table = # of page table entrys = 2^v / 2^m

    • of bits for pg. number = log(#PTES)

      • they’ll give us #PTEs as a power of 2
      • eg. #PTES = 2^14
      • then # of bits for pg. number = 14
    • we have pg. number to figure out which page of virtual memory the address sits in, and then we need an offset to determine where in physical memory this address is
      • pg. offset bits = log(page size)
        • eg. pg. size = 2^10, then pg. offset bits = 10
    • once we have page number, we use it to look up a page table entry
      • this will tell us the corresponding physical memory frame number
        • if valid bit is set, the frame is in use
    • once we have a frame number, we get physical address = frame# * frame_size + page_offset
      • (* frame_size ?)
        1. 4kb = 0x1000 = 2^12

Examples

Address Translation (Process B) [vm_s19]
phys. addr = 18 bits
v. addr = 16 bits

...
  • if we had an address that began with 0xe…, our valid bit in the page table is 0
    • this means there’s no translation.
    • If the address cannot be translated, there is an exception

Other Information Found in PTEs

  • PTEs may contain other fields, in addition to the frame_number and valid_bit
    • eg. read_only_bit
      • would handle cases where you try to write to the memory address
    • eg. bits to track page usage
      • reference (use) fit
        • has the process used this page recently?
      • dirty bit
        • have contents of this page been changed?
      • these bits are set by the MMU, and read by the kernel (more on this later)

How Large Are Page Tables?

A page table has one PTE for each page in virtual memory

  • page table size = (number of pages) * (size of PTE)
  • number of pages = (virtual memory size) / (page size)
  • from this point on, page table size refers to the amount of space a page table occupies in memory
    • #PTEs * page size
  • example
    • 64KB v.mem, 4kb pages, 32 bits per PTE
      • page table is 64 bytes
  • page tables for larger virtual memories are larger

Problems

  • page table with maybe a million entries, but our program is only a few kilobytes large
    • only a few PTEs will be used, out of millions available
  • our page tables are really large, but mostly empty for most programs
    • not efficient
  • good at preventing external fragmentation, but becomes deadweight lots of times
    • waste of space
      • whose space are we wasting? The kernel’s
      • every process has a page table

Summary: Roles of the Kernel and the MMU

Kernel

  • manage MMU registers on addr. space switches (context switch from thread in one process to thread in a different process)
  • create and manage page tables
    • creates page table when process is created
  • manage (allocate/deallocate) physical memory
  • handle exceptions raised by the MMU

MMU

  • translate v.addr to phys.addr
  • check for and raise exceptions when necessary
  • the kernel must also notify the MMU to use new page tables
  • must do at least one address translation
    • it must translate the PC address to a physical addr
      • add $r0, $r1, $r2
  • lw $12, X($s3)
    • each loadword instruction requires at least one translation
  • accessing memory is expensive
    • add, sub, add, add, mult, mflo, mfhi, add
    • for each of these assembly instructions, the MMU has to translate an address
      • the PC that points to them needs to be translated
      • probability that these sequential instructions live on the same page?
        • relatively high
        • spans at most two pages
          • why are we translating their addresses individually, each time?
    • if we have an array, our index values occupy sequential addresses
      • so, there’s a pretty good chance that most arrays we have will fit in a single page of memory
        • yet, our MMU will still translate the v.mem addr of each of these values
        • we want to reduce how often the MMU has to go to RAM (to find the page table) for page-to-frame mapping

Translation Lookaside Buffer (TLB)

  • Caches our page-to-frame mappings
  • When we have a v.addr, and we obtain a page number, we first check the cache instead of going to the page table which resides in RAM
    • much faster to access this than RAM

TLB Usage

What the MMU does to translate a virtual address on page p

if there is an entry (p, f) in the TLB, then
    return f
        ; TLB hit
else
    find p's frame number (f) from the page table
    add (p, f) to the TLB
        ; evict another entry is full
        ; to decide who to evict, can use a dirty bit
    return f
        ; TLB miss
  • If the MMU cannot distinguish TLB entries from different address spaces, then the kernel must clear or invalidate the TLB on each context switch from one process to another
    • as_activate(...)
    • if we don’t clear, we will have page-to-frame mappings in our TLB for the incorrect process
  • This is a hardware-managed TLB
    • the hardware goes to RAM and gets a new page-to-frame mapping after a TLB miss, etc
      • problem with hardware doing the work is that the hardware needs to know exactly what the page table entries look like
      • needs to know exactly what our page table implementation does
      • essentially, the hardware specifies, to the OS, how paging works
      • very fast, but restrictive from an OS

Software-Managed TLB

MIPS has a software-managed TLB, which translates a v.addr on page p like so

if there is an entry (p, f) in the TLB, then
    return f
        ; hit
else
    raise exception
        ; miss
  • In case of a TLB miss, the kernel must
    • determine the frame number for p
    • add (p, f) to the TLB, evicting another entry is necessary
      • for q3, we randomly evict an entry
  • After the miss is handled, the instruction that caused the exception is retried

The MIPS R3000 TLB [vm_S27]

64 bits

  1. upper 20 bits : page number
  2. next 6 bits : PID (not used)
    • this PID can be used to match an entry to a process, so that it will not be used if the active process doesn’t own the entry.
    • Not used in MIPS R3000… they put it there but don’t use it

A More Realistic Virtual Memory

There has to be a better way to do virtual memory that better represents what our virtual memory actually looks like

  • Our page table has lots of invalid entries
    • not what our actual memory looks like
  • The kernel itself lives between memory 0x8XXXXXXX to 0xFFFFFFFF
    • it is a part of a process’ virtual memory space, but the process will never use this section of memory

CS350, 2017-06-15

Large, Sparse Virtual Memories

Virtual memory may be very large

  • MIPS: V=32, max virtual memory size is 2^32 bytes (4GB)
  • x86-64: V=48, max virtual memory size is 2^48 bytes (256TB)

Much of the virtual memory may be unused

  • testbin/sort needs only about 1.2MB of the full 4GB virtual memory it runs in
  • The amount of data we might be allocating for virtual memory pales in comparison to the amount of memory we actually need

Application may use discontiguous segments of the virtual memory

  • In the testbin/sort address space, the data and stack segments are widely spaced
    • why?

Limitations of Simple Address Translation Approaches

  • A kernel that uses simple dynamic relocation would have to allocate 2GB of contiguous physical memory for testbin/sort virtual memory
    • even though sort only uses about 1.2MB
  • A kernel that uses simple paging would require a page table with 2^20 PTEs (assuming page size is 4KB) to map testbin/sort address space
    • this page table is larger than the virtual memory that sort needs to use…
    • most of the PTEs are marked invalid
    • this page table has to be contiguous in kernel memory

Segmentation

  • Instead of mapping the entire v.mem to physical, we can provide a separate mapping for each segment of the virtual memory that the application actually uses
    • from slide vm_28, we don’t need to keep track of the near 4GB of wasted/unused addresses
    • what if we only stored the mapping for the red, green, and blue memory sections?
  • Instead of a single offset and limit for the entire address space, the kernel maintains an offset and limit for each segment
    • If I have 3 segments: code, data, stack, my MMU will have 3 sets of registers
      • for translation, need to determine which segment an address belongs to
      • then, do simple dynamic relocation math to translate the v.addr to phys.addr
  • With segmentation, a v.addr can be thought of as having two parts
    • segment ID
    • offset within segment
  • with K bits for the segment ID, we can have up to
    • 2^K segments
    • 2^(V-K) bytes per segment
  • The kernel decides where each segment is placed in physical memory
    • fragmentation of physical memory is possible again, although the trade-off seems worth it
\# segments
\# bits for segment number = ceil(log(# segments))

see [vm_S32]

Translating Segmented Virtual Addresses

  • The MMU needs a relocation register and a limit register for each segment
    • let Ri be the relocation offset for the ith segment
    • let Li be the limit for the ith segment
  • To translate v.addr v to a phys.addr p:
split p into segment number (s) and
    address within segment (a)

if a >= L_s, then generate exception
else
    p = a + R_i
  • As for dynamic relocation, the kernel maintains a separate set of relocation offsets and limits for each process
    • also changes the values in the MMU’s registers when there is a context switch between processes
  • We never allocate memory for address space(s) we don’t use
  • Amount of data we need to store to manage these extra limits and offsets is negligible (relative to the entire memory system)

Segmentation Fault

  • Attempting to read or write to an address that is not in a segment for which you have permission to do so
    • read/write memory outside of your segments

Segmented Address Translation Example

Limit Reg 0: 0x2000 ; Reloc Reg 0: 0x3 8000
Limit Reg 1: 0x5000 ; Reloc Reg 1: 0x1 0000

Only two segments in address space, so...
    \# bits for seg.num = 1

v = 0x1240 = 0001 0010 0100 0000
; segment = 0
; offset = 0x1240
; p = 0x39240

v=0xa0a0 = __1__010 0000 1010 0000
; segment = 1
; offset = 010 0000 1010 0000 = 0x20a0
; p = 0x120a0

v = 0x66ac
; segment = 0
; offset = 0x66a0
; outside of limit : exception

v = 0xe880
; segment = 1
; offset = 0x6880
; outside of limit : exception

__note__
if addr cannot be translated
    exception
else
    ...

Problem(s)

We’ve solved the issue of allocation egregious amounts of unused memory, but we’ve introduced the problem of externel fragmentation

  • We are still trying to allocate contiguous regions of physical memory
    • these regions are variable in size
    • every process will have different code/data/stack segment sizes
    • when storing a new process and creating a new address space, the kernel tries to find a free segment of memory
      • if no contiguous region, can’t start process
      • can defragmentate, but that affects performance
  • External fragmentation can be solved
    • OS/161 uses segmented memory
      • different, though. Does not specifically encode a segment number
      • A3: combine segmentation with single-level paging
        • before, we had a single page table for the entire address space
        • when combining the two techniques, have a page table for each segment
          • 3 segments : 3 page tables
          • this works because we will now divide segments into pages and map each segment page to a physical frame (no external fragmentation)
          • and, our page table will only be tracking regions of the address space we’re actually using

Two-Level Paging

  • Instead of having a single page table to map an entire v.mem, we can split the page table into smaller page tables, and add a page table directory
    • instead of one large, contiguous table, we have multiple smaller tables
    • if all PTEs in a smaller table are invalid, we can avoid creating that table entirely
  • lower level is where we map frames to pages
  • upper level tells us if there are any valid mappings
    • if no valid mappings, won’t create sub-page-table
  • each v.addr has three parts (somewhat more complicated now)
    • level one page number
      • used to index the directory
    • level two page number
      • used to index a page table
    • offset within page
our v.addr looks something like

DDPP OOOO ...

Old Example [vm_S36]

We have a page table with 16 entries, but only 7 are valid

  • We will have a directory with 2 page tables
    • Fewer invalid entries
    • Fewer total entries

Address Translation with Two-Level Paging

  • The MMU’s page table base register points to the page table directory for the current process
  • Each virtual address v has three parts: p1, p2, off
  • How the MMU translates a virtual memory
    • index into the page table directory using p1 to get a pointer to a 2nd level page table
      • directory indices store a pointer to a page table (or is NULL is no page table entry has no valid entries)
    • if the directory entry is not valid, raise exception
    • index into the 2nd level page table using p2 to find the PTE for the page being accessed
    • if the PTE is not valid, raise an exception
    • otherwise, combine the frame number from the PTE with off to determine the phys.addr (same as for single-level paging)

Example [vm_S38]

The number of offset bits still depends on the page size

Limits of Two-Level Paging

  • One goal of two-level paging was to keep individual page tables small
  • Suppose we have 40-bit virtual addresses (V=40)
    • size of a PTE is 4 bytes
    • page size is 4KB (2^12 bytes)
    • we’d like to limit each page table’s size to 4KB
      • we want a page table to occupy a single page in memory
        • this is (more) efficient
        • if our page table occupied multiple pages, we’d have a bunch of TLB or some such page misses
        • page table size / pte entry size = # of entries that can fit in a page
  • Problem
    • for large address spaces, we may need a alrge page table directory!
      • there can be up to 2^28 pages in a virtual memory with V=40
      • a single page table can hold 2^10 PTEs
      • we may need up to 2^18 page tables
      • our page table directory will have to have 2^18 entries
      • if a directory entry is 4 bytes, the directory will occupy 1MB
  • this is the problem we were trying to avoid by introducing a second level

CS350, 2017-06-20

Assignment 2B

  • Builds off of 2A
    • Some marks are dedicated to retesting 2A
      • 18 marks for onefork, pidcheck, widefork, forktest
    • There are some 2B tests with 2A implementation dependencies
      • eg. hogparty uses fork
  • Remaining marks are dedicated to int execv(const char *prog, char **args)
    • We have a process that is executing some program
    • Call execv, which changes the program the process is running
      • will destroy currently running program
      • create a new address space
      • load new program
      • begin executing new program
    • Can use fork to implement a part of execv, but execv does not fork a new processes
  • Params
    • execv should support programs that take parameters
    • Need to get all these params into the kernel
      • We’ll load a new program
        • Need to throw old address space out
  • Runprogram
    • execv is very similar to runprogram (kern/syscall/runprogram.c
      • recommend
        • make sys_execv copy the contents of runprogram into it (this is your starting point)
    • Runprogram is used to load and execute the first program from the menu
      • opens the program file using vfs_open(progname, ...)
      • creates a new addrspace (as_create)
      • switches the process to that addrspace (curproc_setas)
      • then activates the addrspace (as_activate)
        • as_activate clears the TLB
        • when we change the program that is running (and creating a new address space), need to clear the TLB mappings for the current process
      • using the opened program file, load the program image using load_elf
        • load_elf helps, for defined data segment, determine its size and properties
      • define the user stack using as_define_stack
        • this stack is limited to 12 pages, and no more
      • after we’ve defined the stack, we need to call enter_new_process
        • with no params
        • the stack pointer (determined by as_define_stack)
        • and entry point for the executable (determined by load_elf)
    • This is the code that executes when you type ‘p’ in the kernel menu
    • Note
      • in execv, we are not creating a new process, so we can’t just use runprogram. However, runprogram is a good place to start
  • execv
    • Copy number of arguments and copy them (the arguments) into the kernel
      • copy from the user addrspace into the kernel
        • there are functions to help do this
    • Copy the program path into the kernel
      • need to copy this into the kernel because we’re destroying the old addrspace
    • Some steps from runprogram
      • Open the program file using vfs_open(…)
      • Create the new addrspace, set process to use new addrspace, and activate it
      • Using the opened prog file, load the prog image using load_elf
    • Need to copy the arguments into the new addrspace.
      • Consider copying the arguments (both the array and the strings) onto the user stack as part of as_defined_stack
        • push, in a very specific way, all the params I had extracted in step 1 (and the path?) onto the stack
        • may need to modify as_defined_stack to do this part
    • Delete old addrspace
      • We don’t delete the old addrspace earlier because some steps above may fail. We want to return an appropriate error code that can be handled in a friendly way.
        • If we delete the addrspace after the 2nd step, we have to panic when something goes wrong in steps (3) and (4)
    • Call enter_new_process with address to the arguments on the stack, the stack pointer (from as_defined_stack), and the program entry point (from vfs_open())
  • Issues
    • When copying from/to userspace
      • Use copyin/copyout for fixed size variables (integers, arrays, etc)
      • Use copyinstr/copyoutstr when copying NULL terminated strings
    • Useful defines/macros
      • USERSTACK (base address of stack)
      • ROUNDUP (useful for memory alignment)
    • Common mistakes
      • Remember that strlen does not count the NULL terminator. Make sure to include space for the NULL terminator
        • must add 1 to the length
      • The array is also NULL terminated
        • char **params
          • last entry is NULL
          • count elements one at a time until NULL
          • need to allocate an array in the kernel to hold all these params
          • each param is a NULL terminated string
            • allocate sufficient memory to hold this NULL terminator
      • User pointers should be of the type userptr_t
        • eg. the interface for sys_execv should be…
          • int sys_execv(userptr_t progname, userptr_t args)
      • Make sure to pass a pointer to the top of the stack into enter_new_process
  • Alignment
    • Byte alignment
    • When storing items on the stack, padd each item such that they are 8-byte aligned
      • ints, bools, etc
      • eg. args_size = ROUNDUP(args_size, 8)
    • Strings don’t have to be 4 or 8-byte aligned. However, pointers to strings need to be 4-byte aligned
    • USERSTACK
      • Argument strings (each string is NULL terminated)
      • Argument array. Last entry is NULL
    • Top of stack ——–
  • Advice
    • get execv working for programs without parameter handling
      • hogparty
      • sty
    • once those are working, start tinkering with program arguments
      • first, implement something that determines # of params (step 1)
      • second, allocate kernel space for them (step 2)
      • third, copy params into step 2
    • print these values out. Make sure you’ve gotten these arguments out of the old addrspace correctly
      • once this is done, only then should you start putting them on the stack

Multi-Level Paging

  • We can solve the large directory problem by introducing additional levels of directories
  • Example: 4-level paging in x86-64 architecture
  • Properties of Multi-Level Paging
    • can map large virtual memories by adding more levels
    • individual page tables/directories can remain small
    • can avoid allocating page tables and directories that are not needed for programs that use a small amount of v.mem
    • Main issue
      • TLB misses become more expensive as the number of levels goes up, since more directories must be accessed to find the correct PTE
        • looks up first page table
        • goes to next page table
        • until it finds the final page table
        • is invalid… fuck
      • goes to RAM as many as X times for X-level paging
      • not mention, the kernel itself is in v.mem, so we need to translate those memory addresses as well
  • Add levels until each page table can fit in one page
    • This probably means we’ll have a lot of page tables
    • eg. in a 48-bit addr architecture, we only need 4 levels, so it’s not so bad
  • Example?
    • Page offset
      • if pg. size ix X bytes, pg. offset is log(X) bits
        • eg. 4KB pg. size => 2^12 bytes => 12 bits for pg. offset
        • our # of bits for pg. offset is only dependent on the pg. size
    • How many PTEs on a page?
      • given size of PTE
      • PTEs = pg. size / sizeOfPTE => 2^12 / 2^2 = 2^10 PTEs per page

        • If we want to keep our page table in one page, we need to figure out how many entries we can fit onto a page
        • Notice we don’t figure out how many levels we need until we know the number of PTEs per page
    • of bits for pg. number = log(#PTEs per page) => log(2^10) = 10

    • | ... | PB | PB | PB | PB | OFFSET |
      • from our example
        • | 10 | 10 | 12 |
          • 32-bits
          • and we have 2-levels for our paging
      • A more mathematical method
      • NUM_LEVELS = ceil((VBITS - OFFSET BITS) / PG NUM BITS)
        • VBITS = # bits for v.addr
        • OFFSET BITS = page offset bits

CS 449

Focus on target user groups.

  • Look at different types of people in user group
  • Need to create a participant pool
    • Should be same type

Understanding Your Users: Exploratory Studies

Questionnaires

  • Open-ended and closed-ended questions
    • Multiple choice, matrix questions, scaled questions, semantic differential and likert scale questions are closed-ended
    • Unstructured, explanation, completion, and association questions are open-ended

Observations

  • Active/passive particpation, complete participation, non-participatory
  • Naturalistic and controlled
  • Record artifacts users manipulate
  • Use codes and symbols
    • Things are happening too fast, use faster identification symbols that can be easily decoded
  • Separate tasks, goals, motivations
  • Separate actions and body language
  • Separate observations and interpretations
    • The former doesn’t necessarily lead to the latter
      • eg. Smiling doesn’t always mean happy
  • Participants your side notes separate
  • Separate “says” and “does”

Interviews

  • In-depth discussion of the topic with a participant
  • Usually one-on-one
  • Written, audio, video recording options (requires consent)
Structured

Not much room to ideate and conceptualize. Interviews are very guided.

  • Same set of questions
  • Standardized process
  • Little freedom of expression
  • Often self-reported
Semi-structured

Other stories and questions that occur can be integrated

  • Structure isn’t as strict, and room for movement is available
  • Has a list of guiding questions/topics
    • Leading questions influence the response in some way, usually by using implications
      • Should be avoided, because they don’t provide unbiased results
  • Often preceded by observation
  • One of the most popular
Narrative (Unstructured)

General direction of where the interview wants to go

  • Focus and objective guides the discussion
  • Open-ended questions
  • Freedom of expression & little control
Focus groups

Usually moderated, and directing conversation, but allows groups of people to develop conversations themselves.

  • Semi-structured
  • Moderated
  • 6-10 homogeneous strangers
  • May permit discussion
  • Emerged in the 1940s

Diary/Camera Studies

  • Includes a mechanism (diary or camera) to record/describe relevant activities in everyday settings
    • For external validitiy, time and place matter
      • Thus, providing diverse environments, the additional data provides better, more applicable responses
  • Longitudinal
    • “How do you feel at this moment?”
    • These questions spread across periods of time
  • Data recorded by participants based on provided guidelines

Diary study

  • A log of activities/behaviours you can use over a period of time
  • Highlight things that stood out over the course of the day
  • Photos provides better insight than simple words
    • Shows habits and behaviours over a time-frame that is often missed because we don’t keep track of them explicitly
  • Two weeks to two months
    • Depends on what is being investigated
    • Requires individuals that express information easily

Participatory Design

  • Participants are given design elements
    • Get individuals from your target audience to construct their ideal experience in real-time
      • Get answers quickly, and apply updates quickly
      • However, regarding reactivity, people kind of forget about generalization. They get caught up in the creative process that they forget about useability
  • Helps to understand values and uncover mental models

Ethnographic Field Studies

  • Natural environment, everyday life
  • First-hand participation in users’ activities
  • Description of the scene, key events, key actors, key artifacts, and actions
  • Combination of observations and interviews
  • Focus on objective behaviours

How can we improve the experience of the cruise head chef?

  • First, analyze his tasks
    • Wakes up, checks emails and prepares
    • Meeting with his chef team
      • Interacting with chefs, and team
      • Instructions for the day
        • Cannot be done remotely
    • Invent(?)
    • Testing(?)
    • Interacting with potential customers

Ethnographic Field Studies = Observations + Interviews + Natural context

Contextual Inquiry

  • Natural environment, everyday life
  • First-hand participation in participants’ activities
  • Relatively short (several hours)
  • Research heavily involved in the process and constantly asks questions
  • Mostly rely on self-report data

Understanding Your Users: Analyzing Qualitative Data

Row-qualitative-data is “fuzzy data”. It’s not actionable yet

  • Notes on cards –> Review the cards –> Sorting and grouping –> Smaller subgroups –> Themes in Data
    • This is our affinity datagram
      • Use all data
      • Use colour
        • eg. separate what people say from what they do
      • Regroup often
      • Use fresh view
      • Give it time
      • Trust

Self-balancing electric scooter (hover board)

  • Observation 1
    • Unboxing
      • Manual first
        • Doesn’t look at it. Thinks he can get it done. Goes back to it later.
      • Then charger cable
      • Then main item
    • Battery state(s)
      • “I think when it gets to yellow…” –> Mental model
    • Testing it out
      • Tried it out, didn’t work well. “I have to read the manual”
      • Trying it with one foot first
        • Fell, and kept trying but with another foot
          • Why does/should it matter?
      • Lean forward –> move forward
      • Lean back –> backward
  • Observation 2
    • Manual first, and actually looks through it
      • “Hope we don’t have to charge for 24 hours”
      • Remote starter?
    • See charger, a lot smaller than expected
    • “Ordered black, but got green.”
    • LED, potentially for battery indicators
    • Went back to look through manual before trying it out

Quiz 1(?)

Talking about top ten key points of innovation, Guy Kawasaki gives an example with a car key

Who developed the concept of persona and what it is about (briefly)

  • Creating a fictional character that embodies the characteristics of who you’re studying

What Mobile-first design principle and what benefits does it provide?

  • Progressive UI
  • Design for mobile first, then expand to larger view-ports. Space-limitations and context allows better focus
    • Content-focused approach for UI
  • Mobile is ubiquitous—it is everywhere
    • Phones are much more personal and satisfying. It is your alter ego, fundamental to everything you do

Understand Your Users: Exploratory Studies

Exploratory Study

Motivational system
  • Goals and tasks (need)
  • Desirabiltiy (want)
  • Emotional charge (fears, frustration, pleasure)
Contextual knowledge & beliefs
Cognitive (mental) model
  • A cognitive representation of how something works/is organised
  • Based on previous experience & beliefs
    • defines reasoning

Enlightened trial and error succeeds over the trials of a lone genius

Translating Needs into Functionalities

Make data actionable

Adjust personas
  • Make them more colourful and detailed, based on generalized characteristics of your participants that you didn’t account for previously
    • There are likely several
Affinity diagrams
  • A sense-making tool for qualitative data
    • Notes on cards –> Review –> Sorting –> Subgroups –> Themes
Breakdowns
  • Where and when things go wrong in individuals work practice
  • Points in time or space when individuals have a problem accomplishing the task that should otherwise be easy, given the tools they’re using
  • Unpacking the tacit dimension for possible design solutions
Cultural model (assignment 2)
  • External influences
    • Important because work takes place in a culture, which defines expectations, desires, policies, vaues, and work approach itself
  • Includes
    • Influences (bubbles)
    • Extent of influence (size of bubbles, overlap)
    • Influences (as arrows with direction)
    • Breakdowns
Artifact models
  • Physical objects that support the work (created and/or used in the process)
    • Because you want to know what objects people need and interact with
    • Also applies to applications as well. These can be described using artifact models because they involve interaction
  • Sketch or photo
  • Complete with comments and notes regarding
    • Structure
    • Related purpose and tasks
    • Functionality

Creation of artifact models

  • Based on our findings and cultural model, we have inspirations for creating our artifact models.

Identify right time and place

Physical model
  • Because you want to known how people adapt their environment to accomplish work
    • Structures that limit and define space
    • Walls, desks, file cabinets, tables, chairs, etc
      • Things used in the process
    • Hardware, software, communication tools
    • Artifacts and their location in relation to each other
  • Practically
    • How a chef on a cruise can observe his kitchens
    • How far a chef has to walk around
  • Complete with comments and notes
  • Not too detailed, just acknowledge that these things exist

Example

  • Art library, workspaces, etc
  • Printers are far away, so that’s a breakdown, because the user is too far
  • Door to oft-used room is on the opposite side of the wall –> breakdown
  • Tall people block the lecture-hall screen for people behind –> breakdown
Sequence model
  • Sequence of work steps and the intention behind steps
    • Because you want to know how work is organized in stages
  • Includes
    • Intent behind step
    • Triggers that initiate sequence
    • Steps, at a high-level of details (actions, not movements)
    • Loops and branches showing order and iteratio
    • Breakdowns

Example (Hoverboard model)

  1. Beginning: Open the box
    • Difficulties? Nah –> No breakdown
    • Trigger? Arrival of the package | | V
  2. Scan the inside of the box | | V
  3. Picked up manual
    • Expected to look through it, but usually didn’t
    • Breakdown: Puts the manual away without reading
    • Trigger?
Flow model
  • Directions of communication and coordination
  • Defines how work is broken up across people and how people coordinate
  • Includes
    • Interviewee (in the middle)
    • Other groups/people (circles)
    • Physical/virtual places (usually rectangles)
    • Artifacts as they pass between people
    • Breakdowns (where things go wrong)
...

Create Design Ideas

Creativity: process of producing a new idea which has value to someone

Nature v. Nuture

During brainstorming, we prefer quantity over quality

  • Generating ideas: memories –> ordinary –> extraordinary
    • How do we get to these extraordinary ideas?

Create Ideas

Preparation

  • Define the constraints
    • Goals, parameters of the challenge, resources, time
  • Knowledge and understanding around the challenge, both academic and casual
  • Assumptions can be challenged
    • eg. a restaurant: what are some assumptions?
      • You order food there
        • Is this a challenge-able assumption? Sure.
    • This is how we can achieve new ideas/concepts

Provocation

  • Overcoming associative limitations
    • Rules we know about the world or some area
      • A while ago, we didn’t really see how we could combine computers and phones
      • Now, smartphones bridge the gap better than ever
  • Design fixation
    • When you know something works (or a solution), and you cannot think of any other solution
      • Don’t use design solutions too early, or you get fixated on it
  • Concept of po by Edward de Bono
  • Force of habits
  • Framing and reframing problems
  • Practice true randomness
    • It’s really hard to be truly random…
      • Think of some “random” word
      • Every day, try to think of a random word. This can help create new connections
  • Connect and combine
    • How can this random concept relate to something you’re doing
  • Change the routine
    • Do something different: introduce new factors into your life

Incubation

  • Mindful procrastination can sometimes be helpful
    • When actively thinking abouting something/brainstorming –> beta waves
    • When resting –> alpha waves
      • Need to approach the problem first: give a task to your subconsciousness
      • Different aspects of creativity require different brain activity
  • Most ideas are formed subconsciously

Eureka moment

  • An idea that might solve the challenge is pushed to the conscious level
  • Usually difficult to explain how you came up with this idea
  • Always write it down in the moment, no matter what

Verification

  • All ideas are rough when they are first visualized
    • Get it through the criticism
  • Be optimistic –> Give your crazy ideas a chance
  • No right answers –> Only working solutions

Realization

Sketches

Illustration of how the basic concept works

  • Low-fidelity, fast
  • Supports brainstorming
  • Speeds up your work
  • Doesn’t necessarily have to look good
  • Supports communication: allows you to talk about ideas
  • Tells a story
    • eg. a problem that needs to be solved
User stories

As a user or persona, I want/need {action} so that I can achieve some {goal}

  • Helps us avoid forgetting simple things
    • People are going to be using your application, so it might help you avoid forgetting things like navigation, etc
  • Keep it simple
  • Keep breaking them down
    • Example
      • As a user, I want to send an email…
        • Need to input recipient addresses
          • As a user, want to have address suggestions for quicker searches
        • Want to enter a message
          • Might want to format text
    • We’re going from higher levels to lower levels so that we can focus on particular aspects that we need to work on
  • Have acceptance criteria
  • A communication tool
  • Keep them visible
  • Prevent dead-ends
Wireframes

Static representation of the UI layout and user flow

  • Quick, cheap, easy
  • Used as the documentation
    • Communication between designers and developers
  • Using pixelated widgets
  • Main groups of contens, structure of content
  • Only basic visualization

Vs. Mock-ups?

  • Mockups are the highest fidelity. Mockups are much closer to the actual application, and request specific design aspects
  • Blueprint vs. photo of the application

Design

Interface

  • A surface/place where two independent systems, bodies or spaces meet/form a common boundary, and communicate with each other
  • Something that represents an underlying system?
    • Has encoded information as to how it should be interacted with
      • eg. Push bars on doors indicate push-to-open
      • eg. Automatic doors indicate you should just keep walking
    • When we approach these components, we understand the information they encode based on our own mental models and/or previous experiences
      • In our interfaces, need to find a way to interact through different aspects of the interface, allowing the user to understand how to interact with it as well
  • A communication channel

Communication

Exchanging of information

Semiotics

The study of signs and symbols

  • Sign
    • Anything that communicates a meaning
    • Representamen (signifier)
      • The form of the sign
        • eg. The soundwaves that are heard as “chair”
        • As signifiers change, interpretants change in real-time
    • Interpretant
      • What people make of the sign
        • eg. What you think of when you hear and interpret “chair”
        • Not guaranteed to match the signified object
    • Object (signified)
      • Actual reference of the sign
        • eg. The actual chair
Signifier
  • Indicators of any type that communicate the action needed so the affordance can take place
    • A play button, pointer-cursor, door-knob indicate a specific action (click, turn and pull, etc)
Affordance
  • The possible use for an object when interacting with it
    • Keyhole: shape of a key, indicating you can insert a key to interact with it
    • Baby chair: put a baby in it
Constraints
  • Negative affordances: restrictions that limit the possible actions available with an object
    • eg. A fence indicates keep-out
    • Physical
      • Caused by physical features, eg. fences
    • Cultural
      • Based on what is culturally accepted, eg. driving on the left side of the road, posting someone else’s work online
    • Semantic
      • Based on the meaning of the situation, eg. “do not disturb” signs mean don’t enter
    • Logical
      • Use reasoning to determine the alternatives, eg. don’t put a square into a circle, lego blocks
    • Sometimes, there is a mix of multiple types
Feedback
  • Conveys effects of user’s actions
    • Makes sure the user understands their action was received
      • eg. Loading spinners, confirmations
  • Location
    • Where am I in the process
  • Current status
    • What’s happening right now?
      • eg. Loading, someone is typing, etc.
  • Future status
    • What’s next, what should the user expect?
  • Outcomes
    • What just happened?
      • eg. Completion, etc
  • Time
    • How many steps are left, how much time is remaining, loading time
  • Reasons
    • Why do you do what you do?
  • Presence
    • Process has input on the system

Why do we want feedback?

  • So the user knows something is happening. But why do they want to know that?
    • Prevents users from trying invalid input?
      • eg. Quitting during a process when they don’t realize it
  • In general, actions require reactions

Feedback Loop

  • Speed: influence decisions
    • What the reaction is for. If it takes too long to get feedback, the user might assign the reaction to something else
    • Speed should correspond to expectations
      • If I start download, I should see the spinner/loader immediately
  • Context
    • Meaning of your feedback
  • Motivation
  • Measurability
    • Provide comparisons

How do we find these loops?

  • First, need to look at actions (esp. those that are repeated)
    • What triggers them
Discoverability

Whether it’s possible to figure out how to use an object by interacting with it

Findability

  • Whether it’s easy to find the content
  • F-patterns for reading web content (sp. Google search results)
  • Applications/patterns
    • Important info in first 2 lines
    • Lots of meaning in first 2 words
    • Variation in size, visuals (bolding, etc)
    • Bullet points
    • Visual grouping

Learnability

  • Whether it’s easy to learn how to use the functionality
  • Make use of existing practices and familiar interactions. This increases learnability by reducing the number of things to learn
  • Build around exsidawting mental models
    • Goes with familiarity
  • Make use of signifiers and affordances
    • Basically, tell the user as much as possible
Mapping

Indication of the relationship between objects. Often controls.

  • Spacial correspondance
    • Not mapping numbers –> buttons, but rather the number next to a button is “mapped” to that button
    • Switches next to text are mapped to that text/option
  • Examples
    • Elevator buttons: numbers –> floors
    • Thermostat round knobs
      • Makes use of gestalt principles
      • Makes use of culture-specifics and existing mental models
        • eg. turn right for increase, turn left for decrease
Conceptual Model

User’s understanding of how the system works, communicated through the design

  • For people to use a product perfectly, they must have the same mental model as that of the designer
Exercise: Time management application

Individual brainstorm

  • Wake the fuck up
  • No snooze feature because they will abuse it
  • Irresistable alarm-defusal
  • Push-back/delay for scheduled tasks like doing work, because we know they’ll procrastinate
    • Get people’s crap out of their system first so they can sit down and do some damn work
  • Moving scheduled tasks around easily
  • Create tasks
  • Create delay maximums
  • Warning flags for time running out before tasks must be started
  • Task aggregation in a visualized manner
  • Timer that psychologically pushes users to be productive
    • Give fake time

Team ideation and user stories

As a user, I want to wake up after a nap so that I can begin doing work.

> As a user, I want to avoid abusing the snooze button
As a user, I want to create a schedule for myself

> As a user, I need to input tasks
> As a user, I want to see my tasks in an intuitive visualization
As a user, I want to procrastinate

> As a user, I need to complete my assignments
> As a user, I want to be able to chill around instead
As a user, I want to be notified if my ass is running out of time

> As a user, I need to input maximum time allotted
> As a user, I want to receive warnings when my time is running out

Crazy Eights

There are lots of ways to design widgets and screens

  • For one feature create eight layouts in five minutes

From Creating Design Ideas –> Prototype Design

Site/App Flows & User Flows

  • The path a user follows through an application
    • Does not have to be linear, can branch out
  • Goal is to optimize users ability to accomplish a task with the least amount of steps
    • Communicates transitions
  • The former
    • What pages/screens are needed
    • What pages/screens should be linked
    • Help to design a navigation experience
      • You can have multiple screens, but how do they interact with each other? Which buttons do what, etc
  • The latter
    • Microinteractions and responses
    • Help to analyze the efficiency of a task
    • Often attached to personas

Information Architecture

  • Structural design of shared information environments
  • Users flow through your product
  • Catalog user’s information
  • Presentation of the information
  • Decision driving function

Knowledge Organisation/Classification

Taxonomy
  • Practice of classification based on hierarchical relationship
  • Parent-child hierarchies
  • Example
    • Wikipedia content section
    • Category navigation: Fruits & Veges –> Fruits –> Cherry
Folksonomy
  • Practice of classification based on non-hierarchical relationship
  • Public tags and their frequencies
  • Examples
    • Hashtags
Domain Analytics Approach
  • Practice of classification based on sociological-epistemological view
  • Indexing to fulfill a task by specific group
Card sorting methods

Cloased card sort

  • Participants get a stack of cards –> Participants sort cards into groups the researched created
  • While it may be more difficult to sort cards into groups because participants have no control over the groups, it’s not enough of a friction point

Open card sort

  • Participants get a stack of cards –> Participants sort cards into groups –> Participants label groups

Static Representations

Recall, sketches, wireframes, and mockups are stati representations of the product

  • Works for creating design ideas

Prototype Design

Prototypes are interactive design models of the product

  • Used for testing and evaluation
  • Low-fidelity, high-fidelity
    • eg. Paper-prototyping
      • Easy to visualize user flow, but difficult to understand interaction between screens
      • Still, we can explore what happens when a button is selected
        • Basically, can add interaction using arts & crafts
    • High-fidelity prototypes are closer to the final product
      • Has higher level of details
    • Breadth: number of covered featuers
    • Depth: degree of functionaliy
    • Appearance: building means
    • Input methods: device mediation

Low-fidelity

  • Low-tech, partial functionality, simulated interaction

High-fidelity

  • High-tech, “Full” functionality, true interaction

Creating Paper Prototypes

  • One solid base
  • Separate sketches for each screen
  • Input-related elements
  • Separate sketches for overlays
  • Sketches for changing elements
  • Simulate intended layout
  • Consistent style of elements
  • High-level content where possible
  • Minimum colours
  • Should look and feel like a sketch
  • Work fast
    • Make it large, add ideas as they come, make it monochrome, one sketch per screen, use verbal description, preprint widgets

How about testing and evaluation?

  1. Identify testing goals
  • What do you want to know?
    • Tasks we want to investigate can be adhoc/active
      • eg. How would you delete a tile from the homescreen?
        • And when they user tries to do it, they’ll literally look for something (like a close button). If they can’t find it, this is good feedback to work with
  • What aspects of UX are you evaluating?
    • eg. Want to assess findability, efficiency of navigation, etc
  • What aspects are the most risky?
  • What do we want to pay the most attention to?
  1. Identify items to test
  • Which component/features are you testing
    • If we want to assess efficiency of navigation, we want to test the navigation implementation
  • How “deep” do you test each feature
  • Which tasks are you evaluating
  1. Choose testers
  • Identify users group
  • Identify user’s level (novice, experienced, expert)
  • ~5 testers is usually enough
  1. Prepare materials
  • Main prototype with all screens, elements, and input methods
  • Additional materials to make changes on the fly
  • Recording setup (optional, but very helpful)
  1. Assign team roles
  • Ideally, three roles
    • “Computer”
      • When a user “clicks” a button, something should change. The “computer” makes these physical changes
    • Interview
    • Note-taker
  1. Run evaluation
  • The Wizard of Oz (Offline Zero) technique
    • A human simulates the responses of the system
    • In on room, the participant would say something into the mic, and the researcher in the other room will quickly input something to change the screen
      • ie. Not a real computer, just a dude behind the screen
    • Need detailed test-plan with test scenarios
      • So you can make changes/reactions of the system quickly
    • Script of instructions for the facilitator, wizard, participants
    • Procedure for the wizard to properly respond to input from a participant
    • The “wizard”

In general, however

  • Present a task script to your participant
  • Give goals, not directions/instructions
    • You’re investigating how the user would navigate towards the tasks (the directions). If you tell them, you’re defeating the purpose
  • Ask about reasons, opinions, suggestions
    • Get the participant to think out loud
    • When they behaviour what you believe to be abnormally, ask them to talk through what they’re doing
      • What buttons they’re pressing, why, what they expected, etc
      • The idea is to quickly assess something on paper, not that it has to be done on paper

Some things to consider

  • Put the participant at ease
  • Ask questions that qualify the participant
  • What are the triggers and conditions for the activity?
  • Dig deeper if the user is vague/brief
  • What do you notice?
    • These responses can often result in false-positives. Take them with a grain of salt
    • If there’s something they should notice, but they don’t, note that down
  • Ask if things are as they expected (to see, to happen)
  • Note down unanticipated actions (eg. if they want to see everything, but you only show one at a time)
    • Also, paper prototypes (with the right materials) can let you accomodate unanticipated actions
      • eg. the girl colouring the cat
        • She painted the background, something you didn’t anticipate
        • Still, you have crayons, so you just fill it in anyways
  • Participants don’t have to be in your target demographic, but it can be good to consider their preferences

MSCI 311

MODULE 1

Different Approaches to Organizations

Organizations are difficult to define, but we can try

  • 6 blind men
    • Our current understanding of organizations is based on a large amount of peoples’ and consultants’ experiences. However, every one of these individuals only had a partial view of the organization

1A Defining Organizations: Based on a Common Goal

  • A collection of individuals deliberately structured to achieve a pre-determined goal(s)
  • Some aspects of an organization are obvious, some need to be identified on our own
    • Structure & design (non ad-hoc)
    • Goal-oriented
      • There is an extent of planning that is required as well. The organization is self-aware of its goals
    • Personality
      • An organization is a social system, hence social science qualities apply
      • People have their own goals, personalities, and attributes.
    • Somewhat of a permanent structure
      • Has to exist for some time, and be well-defined
    • Use technology
      • Information systems, operation know-how, etc.
    • Interact with the environment and landscape
  • Prescriptive: Tells us what organizations ought to be, rather than what they are

Ideally, we have people working towards a defined goal. However, there are issues with this

  • Goals aren’t always easy to define
    • Can be irrational: visions, ideas, concepts, growth
    • Goals get transformed as they go down the hierarchy.
      • People approach it with their own perspectives and opinions, and sometimes they don’t align with the overall
  • What is the common goal of the University of Waterloo? Do faculties, staff, and administrators have one common goal?

Our definition

An organization is a set of formal and informal constraints that result in patterns of behaviour

  • Formal and informal constraints –> Patterns of behaviour
    • eg. Employees must be at work between 2-4PM (formal)
    • eg. Dress codes are sometimes formal, but often informal
      • Can indicates a culture
    • Don’t tell us what an organization should be, but rather simply, if you want to define an organization, you must look at its patterns of behaviour, and analyze its constraints
  • Constraints regulate patterns of behaviour

1B Understanding Organizational Theories

  • Organizations are ‘man-made’
  • They are not the result of natural evolution
  • Core competency
    • Federal government told universities to show that their resources and efforts are in alignment with their …

Management fads

  • Agile, hackatons, innovation landscapes, reward systems like employee stocks, etc.
    • What makes them management fads? These new ideas are methods of introducing growth and fresh concepts
    • They come and go

Research considerations

Unit of analysis

  • Tells us what theories are focused on: the fundamental element of interest
  • Important to find the most suitable unit of analysis depending on what the research question is
  • What might be the unit of analysis in researching the following questions?
    • What is the effect of market uncertainty on organizationl productivity?
      • Profit year-over-year, …
    • What roles do participants take in organizational decision making?
      • People(?), the decisions being made(?), …
  • If studying a particular company, then results should be very applicable to that company, but it won’t be very generalizable
    • The focal point matters
  • Prescriptive Approaches
    • eg. Take a break for 10 minutes every 50 minutes of work
    • eg. Do the most difficult work when feeling the best
  • Descriptive Approaches

1C Scientific Management

  • Taylor’s Theory?
  • Take people’s work and modularize it
    • Come up with the most optimal way of doing each task, and give workers indepedent tasks
      • Implications in modern manufacturing
    • How do workers react to this kind of management?
    • Very much internal: didn’t care about governments, suppliers, etc.
      • Only tasks conducted by this organization
  • Problems with this approach
    • Limited applicability
      • Physical v. cognitive tasks
      • Individual v. group tasks
    • Undersirable consequences of optimization
      • Repetitive work
        • No control over what is being done and how it is done
        • Workers are replaceable
      • Loss of autonomy
  • Prescriptive
    • Told people what to do, and didn’t care to consider workers’ opinions

1D Bureaucracy

  • Idea: Operate a business rationally and with efficiency
    • Bureaucracies are the backbones of organizations
    • The idea was to make organizations as rational as possible.
      • As soon as someone left the job, all of the knowledge they had is lost
        • Don’t want to re-invent the wheel…
  • Why not make organizations predictable in its structure?
    • This theory was interested in the internal operations of this organization
    • Was prescriptive
      • Weber provided rules as to how the organization should be run
    • Issues
      • Not very reactive
      • Strict hierarchy means information and issues get lost as they travel through the levels

Activity: Apply the following rules to a UW job description 1. The role/office must have fixed and official jurisdictional areas ordered by rules * It’s clear what the position has authority/responsibility over * It’s clear what the position should be doing * Doesn’t matter who is hired (strengths, weaknesses, perspectives), the position is written in stone/policy 2. Positions/roles have a firmly ordered office hierarchy * ie. chain of command * Know exactly who the position reports to, and who reports to the position * Not up for discussion * The higher up the hierarchy, descriptions become more vague (high-level) 3. The activities of the office should be based on written documents (the files) * There are rules, documents, and files that dictate the position and its qualities

Example

  • Mathematics Faculty Computing Facility –> Manager, Client Support Services Inst
    1. External support activities, management of assigned technical projects, internal support activities, computer systems admin, …
      • This position has X key jurisdictional areas that they are responsible for; and, it is clear
    2. Supervises data support, and reports to Associate Dean of Computing
    3. What kind of files would this position generate/work with?
      • Compile documentation of internal space used by clients
      • Provide input into strategic budgeting decisions based on this information
  • If you cannot find specific documents, consider generic files
    • eg. co-op managers have to deal with performance evaluations, etc.
There is no “Organization” without bureacracy
  • Issues don’t arise because bureacracy is implemented. They arise because there’s too much bureacracy
    • It’s not suitable, rules are outdated, rules are too restrictive
    • Sometimes, there’s not enough bureacracy
    • This is a very important aspect of organizations. Finding the right balance is important.
Issues with bureacracy
  • Rules are not always appropriate
    • Clinics “force” you to wait for test results before prescribing medication
      • What if the results are clear without waiting for a lab?
      • eg. Can’t we take shortcuts to get simple antibiotics against strep throat?
  • Rules are hard to change
  • Making decisions based on limited information
    • Every time information moves up on the hierarchy, information gets lost
    • Higher-ups don’t always read entire reports written by lower-level employees

1E Human Relations

Existence of informal organization (social organization) with its own normals, values, and expectations

  • Social organization has a great impact on productivity
  • The Hawthorne studies have had a great influence on modern organizational science
    • Managing involves getting things done through people
    • As such, management should focus on employee attitudes, perspectives, and interpersonal relations
      • ie. individual behaviour
  • Main concern was internal operations
  • Descriptive approach, where they looked to test productivity
    • Gained much insight as to how to improve organizations
Issues
  • Group decision making (to make everyone happy) is not always feasible
    • Too much input –> too difficult to coordinate
    • Mutually exclusive expectations, can’t satisfy them all
  • Cultural change is difficult

1F Systems View

A system is a series of interconnected and interdependent things

  • Sub-components are in continuous interaction with its environment
  • Abstract way of thinking about organizations
  • Unit of analysis
    • Cycle of events that occur

Focal persons and role senders are in a cycle of adaptation

  • Ethan might originally perceive a role based on the job description, but his manager who wasn’t there for the interview might have different expectations
  • This dissonance undergoes cycles of adaptation, until it’s worked out
    • Ethan can be stubborn, which makes the system require more cycles
  • Allon, the manager, sends his expetations of the role in, perhaps, suggestions of improvement.
    • Ethan can change, and start receiving the “right” role
Problems

Very ambiguous level of analysis (chicken & the egg)

  • An entity’s behaviour can only be studied once its subsystems and environment are identified, but you can’t do that unless you understand the entity
  • This approach is very complex and requires detailed definitions of the system
    • This can be difficult to do well, esp. when studying the organization from an external point-of-view.

1G Contingency Theory

  • Best management and organizational design depends on context
  • There is no single optimum design for all possible conditions in an organization
    • The goodness of an organization design depends on a number of variables
    • Just like a person’s behaviour is a function of the person’s personality, perspective, and situation, an organization’s sturcture emerges as a function of its internal and external environment.
      • Based on these relevant factors, contingency theory can suggest the best way to structure the organization
  • This approach to studying organizations has sometimes been criticized as boiling down to recipes for success.
    • In many ways, this approach is not novel
    • Managers have always known that the effectiveness of their management methods depend upon a number of factors
Other Approaches
  • Decision theory
    • Some believe that a manager’s primary responsibility is to make decisions
      • Given this, the decision theory focuses on understanding and improving decision making at all levels in organizations
  • Management science approach
    • Derived from decision theory, management is an exercise in mathematical processes
    • The focus of the approach is optimization

MODULE 2

Introduction

The structure of an organization can be defined as, simply, the sum total of the ways in which it divides its labour into distinct tasks and then achieves coordination among them

2B1 Labour Division

  • Cashier
    • Taking orders, inputting orders into the system
  • Make order
    • Preparing coffees, sandwiches, and or grabbing pastries
    • Bake pastries, breads, etc
  • Cleaning
  • Drive-through

Benefits

  • Specialization, the way in which labour is divided into distinct tasks
  • Expert performance
    • If the task is simple (enough) you can get very good at it
  • Simple tasks mean less training time
    • The more divisions, the quicker it is to learn
  • Minimum dependence on labour
    • Workers are easily replaced

Disadvantages

  • The more labour is divided, the more difficult it is to achieve coordination
    • Makes sense, as you’re adding more variables to the equation
  • Worker alienation
    • No ownership over the task. The worker has no control/responsibility over the task except to just do it

2B2 Design Variable: Coordination

  • Everyone knows what they’re supposed to do
  • Communication (talking, headsets)
  • Screens that show orders and take order inputs
  • Scheduling
  • Training
  • Work instructions/manual for prepping food, etc
    • Visual representations
  • Manager

Requirements

  • Communication, Coooperation/Collaboration (want to do so), Capacity (able to do so)
Mutual Adjustment

Most basic form of coordination

  • Informal communication between two or more people
  • Example
    • Two people crossing a river on a canoe
      • They paddle in coordination by simply talking to each other
  • This simple form is used at all levels of organizations in all organizational types
Direct Supervision

One takes responsibility for the work of many

  • Example: Rowing
    • 1, 2, 4, or 8 rowers + coxswain
      • Coxswain steers, communicates with the rest of the team to do manuevers
      • Gives steering commands, motivation, and feedback
      • 8-man rower boats always have a coxswain
  • In general, direct supervisors and/or managers coordinate the work
Standardization
  • Coordination incorporated when job is designed
  • Standardization of work processes
    • Contents of work are specified, or programmed
    • Specific instructiosn on how to do something
      • Reduces the need for a supervisor
  • Standardization of outputs
    • Results of the work are specified (eg. dimensions of a product)
    • Specific instructions as to what the output should look like
      • Mock-ups, designs, etc
  • Standardization of skills
    • eg. a painter has understandings of the skills required
      • You don’t tell him how to paint and what to paint with
      • You don’t tell him what it should look like, otherwise you wouldn’t need a painter

Exercise

When assembling IKEA furniture, the package comes with assembly instructions

  • This is standardization of work processes
    • Tools are provided, and how to use them is specified
    • Note, there can also be standardization of output, but in this case, you probably don’t need to be given the output specifics to build a piece of IKEA furniture

2B3 Design Variable: Shape of Organizations

Span of Control

How many people should report to a manager, maximum?

  • Software: 6, <5
  • Tim Hortons: 8-15
  • Assembly line: 8-15
  • Academic Units (eg. Chair of the Department of Management Sciences): 26

Context matters

  • Weber used to think that the right number was approx. 7
  • In modern organizations, it is seldom correlated with other factors like industry, workers’ complexity of tasks, etc
  • **Span of control directly affects whether an organization has flat vs. tall structure
Flat vs. Tall

2B4 Design Variable: Decision Making

Another important design variable in determining the organizational structure is the level of centralization, which is a measure of decision-making power.

  • Organizations vary from decentralized (many have decision-making power) to centralized
  • More centralized: decisions are made higher-up in the hierarchy
    • eg. Academic institutions are notoriously centralized
  • More decentralized
    • Have to reduce control for certain positions
    • More delegation of decisions
  • Issues
    • Highly centralized organizations introduce overload
      • Low number of decision makers make a higher number of decisions
    • …and loss of flexibility
      • Have to wait for your supervisor’s supervisor’s manager to make a decision
    • Highly de-centralized organizations have high expertise but reduced consistency and control
      • eg. professors teaching courses

2B5 Grouping of Tasks

Module 3

3A Introduction

What is communication?

  • The sending and receiving of messages between two or more people
    • eg. teaching, gossiping, meeting
  • The exchange of information and transmittion of meaning
  • All procedures by which one mind may affect another

Types

  • Verbal v. Non-verbal
  • Examples
    • Watching the news, reading the news, etc

All human behaviour can be used to communicate?

  • Yes
    • You don’t have to speak to communicate something
Interpersonal Communication

Information is sent from one person to another (or others). This implies a transfer of meaning between parties

  • Social process
    • Since more than one person is involved, social factors will influence transfer of meaning
      • Speaking with interviewers and employers is much different than speaking with friends
  • Context-related
    • The meaning of words changes with respect to context
      • eg. if I look for nails at Home Depot, it’s easy to see I’m not looking for a manicure

3B Shannon’s Information Theory

A mathematical model of communication with significant influence on psychology

  • Source
    • Produces a message or sequence of messages (out of a set of possible messages) to be communicated to the receiver
      • eg. mind conjures a message using brain signals
  • Encoder
    • Operates on the message in some way to produce a signal suitable for transmission over the channel
      • eg. mouth encodes brain signals into audible soundwaves
  • Channel
    • The medium usd to transmit the signal from transmitter (encoder) to receiver (decoder)
      • eg. the air
  • Decoder
    • Performs the inverse operation of that done by the encoder, reconstructing the message from the signal
      • eg. eardrums transform soundwaves into brain signal
  • Destination
    • The person or thing for whom the message is intended

Basic concepts of Information Theory

Uncertainty

Uncertainty is a gap in knowledge –> A measure of the amount of information needed to know the state of the system precisely

  • It contains the number of possible outcomes/events and their probabilities
    • eg. consider X = Ada’s grade in the course. Unless we are told what it is, we have 100 possibilities
      • If we know marks can be no lower than 32, then we’ve reduced the set of possibilities
      • If we know the average (70), then we have a 50% chance Ada’s mark is below 70, and 50% that it is above 70

Why is the game of 20 questions so effective?

  • We reduce the uncertainty significantly (if played well) every turn. 20 questions is more than enough to ascertain the information
Information
Redundancy

Extent to which one part of the message reduces uncertainty in another part of the message

  • The extra information is unnecessary
    • eg. “h _ _ _”
      • What could this word be? We still aren’t sure, but it’s a lot more clear than when we didn’t have the ‘h’
  • Redundancy can be beneficial
    • esp. when safety is important, or when channel is noisy
      • If you want to ensure that the message is transmitted, redundancy can help ensure it is seen
        • Sending a message multiple times but in different mediums ensures it is safely received
      • If the channel is noisy, can lose a part of the message. Redundancy can ensure the full (or close-to-full) message is transmitted

Communication Effectiveness

This concerns the success with which the meaning conveyed to the receiver leads to the desired conduct on his part

  • Encoded message at the source must be the same as the decoded message at the destination
When does miscommunication happen?
  • A message may be altered in noisy or lossy channels, where it may gain or lose bits of information that may significantly change its meaning
    • eg. bad phone signal
  • When the sender and receiver have different priorities
    • In other words, the decode may decode the message correctly, but the destination might interpret it differently, whether on purpose or by accident
      • This sounds like the decoder’s problem too, but whatever…
  • Different people have different categorial knowledge
    • People generally organize knowledge according to a hierarchy of categories
      • We categorize bananas and apples as fruit, which is a sub-category of food
    • Now, consider the communication between a doctor and her patient
      • Her knowledge of organs, symptoms, and diseases is much more complex. Even asking something like “Have you had any prior significant health concerns” can be cause for miscommunication
        • The patient might not know what qualifies as a health concern

3C Communication in Organizations

  • Downward communication usually constitutes
    • Information on goals
    • Job instruction
    • Feedback on subordinates’ performance
    • Examples
      • Quick messages to approve something
      • Quarterly results for motivation
      • Commands and instructions
      • Structural changes from executives
      • Town halls for organizational updates and connections
  • Upward communication
    • Update managers/supervisors on projects
    • Update on issues
    • Provide feedbacks for supervisors to help them
    • Reporting about work accomplished
    • Positive reporting (give information a positive spin)

E-communication

As more organizations become global, and virtual communication technologies improve, much of an organization’s communication becomes exclusively virtual.

  • Emails, instant messaging, texting, video chats, etc
    • These have become methods of choice even when face-to-face communication is an option
  • Virtual communication has the advantage of keeping an accurate trail of the message
    • esp. written form
      • Even videos with transcripts are good enough
    • These messages can be accurately described or traced when needed
  • On the other hand, negative implications include coordination of complex tasks
    • Increase in number of messages does not necessarily lead to better task coordination

Example

Consider a team working on a new product. Any team member will likely receive 150-200 emails a day!

  • This is overwhelming, and has significant implications in shaping how employees handle their work
    • They might end up spending more time replying to emails than usual
    • In meetings, they’d be replying to messages instead of contributing or learning
    • Or, they’ll likely respond to priority messages only
    • They’ll respond quickly, but say nothing important
  • Another implication is its effect on help-seeking and help-giving behaviour.
    • Face-to-face requests are supposedly 34 times more successful than an email
    • If someone emailed you vs. dropped by your office to ask in person?
      • The latter seems more successful (pro-social behaviour)

Module 4: Organizational Environments

Introduction

A system’s view of an organization was our first view of an organization that didn’t live in a vacuum

  • The environment has effects on how an organization behaves

How does an organization handle environmental uncertainty?

4A Organizational Environments and Their Uncertainty

General environment

  • Anything and everything that can affect an organization, whether the it plans for it or not, regardless of whether it’s aware of it or not.
    • Any factor that can potentially influence all or parts of the organization
      • Ecological
      • Cultural
      • Economic
      • Legal
      • Sociological
      • Political
      • Market
  • Examples of factors
    • Minimum wage increases affect some organizations (Tim Hortons) –> Legal
    • Generational shifts in the workforce/customers –> Cultural/Sociological
      • How organizations manages itself (different hires)
      • How it designs and develops its products to serve a different customer-base
    • Change in the political climate –> Political/Legal
      • Affects skilled workforce recruitment
        • Organizations relying on immigration workforces
        • Canadian Universities are experiencing a “Trump Bump,” where grad-school applications in Canada have significantly increased year-by-year
    • Busy hurrican season affects construction/insurance companies –> Ecological
    • Rise and fall of demand in general, esp. bitcoin & crypto-currencies –> Market/Economic
      • Affects decisions that can/should be made regarding the currency
    • Data regulation in Europe affects high-tech companies –> Legal
    • Interest rate changes –> Economic
      • Has various affects on many industries
        • eg. Down –> Stimulates real-estate market
    • Cultural expectations regarding organizational power, management styles, working hours, gender relations, work-life balance –> Cultural
      • eg. in 2009, UW opened a satellite campus in Dubai
        • There was concern regarding the human rights climate in Dubai at the time. Openly-LGBT professors weren’t guaranteed the same working environment available in Canada
  • Also note that some organizations cannot physically care about every factor in the environment

Task Environment

Regarding the final point above, these factors form a subset of general environment factors

  • These are factors in direct influence of the organization’s goal setting and goal attainment
    • eg. customers, demand, suppliers, competition, government

Organizational Set

Set of other organizations that are part of the same task environment of the organization, with with the organization interacts

  • Competitive, co-operative, symbolic vs. substantive
    • eg. GM vs. Toyota
    • eg. GM & Magna (supplier)
  • A symbolic relation refers to licensing agreements
  • A substantive relationship refers to more in-depth co-operation between two companies trying to achieve something together
    • eg. Deloitte + TD in blockchain projects

Enacted Envrionment

What constitutes an organization’s environment?

  • Some organizations do not have sufficient resources to handle every factor
  • Sometimes, two similar organizations have different factors of emphasis
  • Organizations are not rational
    • A = B for one company
    • B = C for another
    • Does not mean A = C

**Portion of the environment that is perceived and acted upon

  • The same actual external envrionment can be perceived differently by different managers
    • eg. Depending on who you ask (the dean, chair, associate chair, faculty), challenges and factors are seen differently
      • For example, some see threats, others see opportunity

What is environmental uncertainty?

Recall, Uncertainty = Information Needed - Information Available

Two variables of envrionmental uncertainty

  • Complexity
    • Number of heterogeneity of external elements that affect the organization
  • Stability, or Dynamism
    • Unpredictability
    • The extent of changes to the environment is unstable
      • They can change in severity, magnitude, etc
      • The more they change, the more dynamic the environment
    • It’s not that it’s changing, it’s that its unpredictable in is changes
      • Seasonal changes is expected, so doesn’t really qualify for instability

4B1: Making the organization more organic

How do organizations manage environmental uncertainty?

Internal Actions

Development of more organic structures (Burns & Stalker studies)

  • Background
    • Studied electronics firms in Britain in the 50s
    • With each firm, they focused on two functional units
      • Manufacturing
        • Low uncertainty
          • Low complexity (simple)
          • High stability (stable)
      • R&D
        • High uncertainty
          • High complexity (complex)
          • Low stability (dynamic)
    • Observed two radically different (and emerging) structures
Manufacturing –> Mechanistic (Bureaucracy)
  • Rigid task specialization
  • Rigid hierarchy
  • Centralized
  • Vertical communication
  • Standardization
R&D –> Organic (Adhocacy)
  • Adhoc: “As it comes”: Things changed depending on task and managers
  • Continuously re-defined tasks
  • Network structure of control
  • Decentralized
  • More horizontal communication
  • Mutual adjustment

As a department, you aren’t dealing with everything that happens in the environment

Summary
  • Manufacturers aren’t dealing with patents, they’re dealing with suppliers
    • Long-term contracts, suppliers
      • These things don’t change often. Manufacturing only really cares about efficiency
  • R&D deals with patents and innovation
    • Lots of changes
Conclusion

The tasks of the organization/department also had an affect on the structure/heuristic of the company

Is one better than the other?

  • No, as different structures serve particular organizations better
  • What is the advantage of having a mechanistic structure in an low uncertainty environment?
    • Don’t need to be as reactive to environmental changes
      • Allows the organization to focus on efficiency instead of worrying about changing
      • Don’t get efficiency when everybody is changing their tasks all the time
      • Recall: Bureaucracy and standardization isn’t bad, it just needs to be at the right amount

4B2: Managing differentiation levels

B. Lawerence & Lorsch studies (Introduction)

  • Background
    • Compehensive study of 100s of companies, in various industry sectors
    • Within each organization, they looked at 3 departments
      • R&D
      • Manufacturing
      • Sales
        • These departments capture a range of environmental factors

Difference between functions in the firms in the plastics industry: collected 4 variables

  • Level of formalization
    • How bureaucratic, basically
  • Planning time horizon
    • eg. How much of your time is devoted to activities that contribute to profits within
      • 1-3 months
      • 3-12 months
      • over a year from now
  • Primary goals
  • Interpersonal orientation

R&D

  • Low formalization
  • Flat structures
  • Conducted infrequent performance reviews
  • Had few written rules & procedures
  • Primary goal was the development ofn ew products (eg. new types of plastics with new characteristics)
  • Employees in R&D structured their work mostly around completing tasks –> task-oriented
  • However, some level of mutual adjustment (discussing with colleagues) was necessary

Manufacturing

  • High formalization
  • Short planning time horizon
  • Efficiency is the primary goal
  • Teams were task-oriented

Sales

  • High formalization
  • Short planning time horizon
  • Primary goals pertain to customer satisfaction and revenue
  • Employees/teams are socially-oriented

Summary

As with the Burns & Stalker findings, the answer was found in the environments that departments were reacting to

  • Different departments have different sub-environments
  • Departments have different primary goals and emphases, and thus react to elements differently
    • Different sub-environments lead to different ways of organizing activities
  • L&L called this differentiation of departments, referring to the difference in orientation of the management in each department
    • B&S referred to it as the difference between mechanistic and organic structures, while L&L refers to it as a different within the org. itself

High differentiation <–> different departments have different structures and orientations

  • Co-ordination issues

Low differentiation <–> different departments have similar structures and orientations

4B3: Increasing Integration

How do we solve this coordination problem, mentioned earlier?

  • Improve integration = Extent of collaboration between departments
    • High departmental differentiation must be matched with high integration

What does integration look like, nowadays?

  • Product manager ~ Individual integrators
  • Emails, forms, Instant messaging ~ Paper systems

Winnepeg Sporting Goods Case Study

  • Attributes of note
    • Medium-sized dealer in toys and sporting goods
    • Manufacturing unit & head office
    • Location: major cities
    • President is a carpenter by trade, so perspectives align with company directives
    • 110 employees
    • $11M annual sales
    • Currently, toy industry is booming (competition landscape)
      • Annual sales exceeding $1.5B
    • U.S. market for toys has experienced remarkable growth in the past decade, currently estimated to have about $20B annual sales
    • Major divisions are headed by managers who’ve been here 15+ years
      • Decision makers are relatives or long-time friends of Campbell, the president
      • Not very tall, departmental/divisional
      • De-centralized
    • Competition is making headways, but WSG is not
    • Organic structure for each department
      • Individuals are let loose to be themselves and contribute with their ideas as opposed to follow guidelines
    • Low expenditure on R&D
      • Only three designers
      • Also, low productivity
  • Structure
    • Functional
      • Departments are created by task, eg. Sales, Plant operations
    • Divisional
      • Organization makes more than just toys, eg. Other operations and divisions
  • Environment
    • Uncertainty?
      • Complexity
        • Lots of competitors –> High
        • Many kinds of toys/products –> High
      • Stability
        • Market is volatile, but trending upwards –> High
        • New companies are appearing –> High

Given its environments, are WSG’s current structure and management practices appropriate? Not really.

  • There’s a lack of innovation, and the current structure contributes to that
  • By being results focused, and due to a lack of R&D, new ideas/product don’t appear often enough
    • Culture should probably be more open to failure
  • Lack of differentiation
    • There’s lots of uncertainty, so we need lots of differentiation
    • Decision makers are friends of the president, and have been around for 15+ years
      • Not many new perspectives here
    • Lack of integration
      • Don’t like meetings, etc
  • No R&D
    • Just three designers working out of manufacturing: no dedicated expenditure resources on R&D
    • If they had R&D, they could have more innovation and higher differentiation
      • Resources
      • Flexibility
      • Not be obsessed with efficiency
  • Note, there’s also a leadership style that doesn’t really work, but that’s for MSCI 211 to discuss
    • Here, we’re trying to discuss it from the perspective of organizational design
Some exam questions

A manufacturer has 50 employees and produces a wide variety of low-volume products for the retail market. Would you expect this organization to be structure along functional or divisional lines? Briefly explain with the help of an example (5 marks)

Divisional
> Due to the large number of products, it'd be infeasible to use a divisional structure: spreads resources too thinly (-)
	> Equipment applies to resources as well
> There would be too many divisions (-)
> Retail market, likely high uncertainty (+)

Functional
> Small # of employees, so functional (cannot have divisional without enough employees (+)
> Too many types of products (+)

For the exam, the two points for Functional should be sufficient to suggest that Functional structure should be the better choice

---

The Burns & Stalker study and conclusion on the effect of environmental uncertainty on organizational structure is considered to be a good example of the contingency approach. Example (6 marks)

> B&S found that there is not one good structure for every situation/organization.
	> Mechanistic organizations had higher specialization, standardization, and rigid hierarchies. These organizations are better suited for low-uncertainty environments
	> Organic organizations use flatter, decentralized structures in an ad-hoc sense, where things change depending on the task and manager. These are good for high-uncertainty environments.
	> These are both great in their respective situations ==> No single strategy that suits all situations
> This appeals to contingency theory, which suggests that structures of organizations are based on relevant factors, both internal and external. There is no one good structure perfect for every case

4C Other internal actions to manage environmental uncertainty

Boundary Spanning Units

How else do organizations manage uncertainty?

  • Collect information about environmental changes and represent the organization to outside agencies
  • ‘Control’ how the organization is perceived
  • Examples
    • Public relations
      • ie. Shape the environment and what they think of you
      • Community relations, Government relations, etc
        • Push as much out there as possible, to get the organization in the media. This helps shapes the public’s understanding of the organization
    • Market researchers

Self-contained units

  • Created ad-hoc in order to respond to emerging issues
    • Usually dissipated when the issue is resolved
  • eg. PDENG Task Force
  • Helps better meet the needs of customers and geographical areas

Information Management

  • Improved planning and forecasting
    • eg. increased mall store hours during the holiday seasons
  • Investment in Information Systems
    • eg. CRM, ERP, KMS
      • Customer Relationship Management System
      • Knowledge Management System
    • Helps organization track data: sales data software, etc
      • eg. Salesforce
        • Keeps track of clients, what they’re doing, follow up with them, etc.
  • And so, Data Analytics becomes an emerging field
    • Use data to make predictions, suggestions, etc
    • eg. Quest/UW has all this data regarding the courses and what students are doing
      • They can potentially use this data

Buffering

Manufacturing organizations typically face uncertainty from both suppliers and customers

  • Suppliers can pose uncertainty to the organization by not supplying input materials on time, or supplying defective/incorrect units

Customers, on the other hand, pose uncertainty by changing preferences, both in the types and quantity of required products

Organizations typically buffer the uncertainty by maintaining larger inventories of raw materials

  • Of course, maintaining large inventories can be expensive.
    • Materials need space to be stored
    • Purchasing more than you need ties up capital that can be used elsewhere
    • May spoil or otherwise get damage as they way to be used
  • Similarly, buffer from uncertainty in the outputs (created by customers)
    • Organizations can produce more than necessary
      • However, stockpiling products has the same downsides as increasing raw material inventories
      • Moreover, customer preferences change unpredicatably
        • Product that cannot be sold is not good
  • Moreover, organization can increase capacity internally
    • More workers, more capacity (but utilized partially), lengthening lead time
      • This helps deal with environmental uncertainty
    • Of course, this increased capacity (or organizational slack) can be very costly

Smoothing/Leveling

Imitating other firms

4D: External actions to manage environmental uncertainty

Establishing inter-organizational linkages

One way that organizations can manage environmental uncertainty is by acquiring direct control over the source of uncertainty

  • This can happen in a number of ways
    • Gaining ownership/control of the supply chain, including suppliers, distributors, and customers
      • eg. Toyota maintains significant control over its suppliers and distributors (eg. dealerships). Toyota’s suppliers are considered part of the company’s production system and are integrated and expected to use the same philosophy and standards
    • By merging with or acquiring competitors
      • Sometimes, to remove the source of uncertainty altogether, organizations will outright merge with or acquire competitors
      • A fairly recent example is the 2010 acquisition of Sybase on the part of SAP

Indirect Influence

Organizations can also provide indirect control and influence over the source of uncertainty

  • This is done through strategic alliances, which are agreements to share resources for mutual benefit
  • Long-term contracts
    • The weakest form of strategic alliances, serve to reduce risk and cost
    • eg. long-term contracts are energy-buying groups
      • In Waterloo, small manufacturing companies band together to sign on to long-term energy-buying contracts, which helps reduce the uncertainty of fluctuating energy prices
  • Joint ventures
    • Strongest form of strategic alliances
    • Serve to create entirely new organizational entities
      • eg. Sony Ericsson Mobile Communications (Sony + Ericsson)

How do you define technology?
> A tool that enables certain actions that otherwise might not be available or is difficult to achieve
	> eg. Phones didn't introduce long distance communication, but it hella helped
> Things that replace humans?
> Makes life easier?

What was a new technology?
> Automation, information systems, new techniques, new processes 

How did that technology impact how people did their tasks, productivity, and the structure of the organization?
> ...

For the purposes of this course, technology = "knowledge, tools, techniques, and behaviour used to transform organization inputs into organization outputs."
> Operations tech: machines, equipments, instruments
> Information tech: information that is received, generated, and analyzed

SCI 207

1.0 INTRODUCTION

Research-based course

PAPER IDEA: THE GREAT WALL PAPER IDEA: IF EXTRA-TERRESTRIAL LIFE DECIDED TO ATTACK US, WE’D BE WIPED OUT

  • 6 short personal research reports to deepen your understanding of any topic you find particulary interesting
  • Present in fun, small-group tutorial discussion
    • Lots of lively discussion and debate

Midterms

  • Two, multiple-choice tests
    • Life
    • Universe & Everything
  • Science content covered during lectures (science literacy, facts, general understanding, etc)
    • Questions directly from powerpoints
    • Supplemental reading materials are also helpful

Final Essay Assignment

  • Due last day
  • One question from each section
    • 800-1200 words each
    • Not meant to involve additional research—rather give you an opportunity to reflect on your learnings from lectures and personal research reports throughout the term
    • Argumentative (personal stance)
      • Construct an argument, and justify your position

2.0 Life

Evolution

Evolution is rather well-understood. It’s a powerful idea—a cornerstone of modern science

  • It explains things in a natural and (relatively) simple way
    • Radioactivity causes mutations
    • Can mathematically calculate rate(s) of mutations
      • Species gradually change in their environments. Better-adapted organisms move forwards
  • Through mutations and adaptation, eukaryotes evolved/bifurcated into various species
  • However, this means we’re not really interested

Origin

  • When, where, and how did life begin?

When

Living Stromatolites
  • Layers of sediment intermixed with different types of microbes
  • “Autotrophs” (photosynthesizing cyanobacteria “phototrophs”) near the top of the layer produce organic compounds
    • They breathe, consume water, etc., to create energy/generate metabolism
  • “Heterotrophs” beneath consume organic “waste,” in a cycle that represents a microcosm of life on Earth today
    • Much of life on Earth has a symbiotic relationship with each other
Fossilized Stromatolites
  • Similarity of layering structure suggests similar origin
  • But is the layering biological or geological in origin?
    • Is it produced by a geological process, or life?
    • eg. Mars
      • Methane gas produced/appears seasonally. Is this an evidence of life? Lots of life on Earth produce methane
      • Question, is this methane a result of a geophysical process, or actual life?
  • Wide variety of structures & isotopic analysis favour a biological origin
    • Carbon sometimes comes in a variety with an extra neutron and 7 electrons
      • Stars make carbon-12 and carbon-13. In nature, this can be predicted using nuclear physics.
      • Normal ratio of C-12 to C-13 is 89:1
    • However, life metabolized C-12 slightly more readily than C-13
      • A C-12/C-13 ratio higher than 89:1 indicates “organic carbon” ==> life

So what?

  • Fossilized stromatolites date back to 3.5 billion years ago
  • Photosynthesis is a very complex metabolic process
    • No way original life could be capable of photosynthesis
      • Origin of life must/should substantially predate this
Microfossils
  • Would be nice to find individual fossilized cells

Challenges

  • Need old rocks not changed by geologicl processes
    • Lots of recycling of rock
      • Tectonic plates, volcanic activity, etc.
    • Also, question: is the structure biological or mineral in origin?
  • Oldest microfossil (3.4 BYA)?
    • Evidence
      • Biological-like behaviour: clustering & habitat
      • High C-12/C-13 ratio in apparent cell wall
      • Different isotope of sulfur inside and around the cell wall
        • Suggests it was metabolising sulfur for energy
Oldest Isotopic Evidence?
  • Higher C12/C-13 ratio is found in 3.85 BYA rock on the island of Akilia
    • Unfortunately, this is metamorphic rock
      • ie. rock transformed by high heat and pressure, which destroys microfossils
  • Evidence supported by…
    • Similar evidence elsewhere
    • Bio-altering isotopic ratios of other elements like iron, nitrogen, and sulfur
  • Relatively complex life was widespread on Earth at least 3.5 BYA (stromatolites), and possibly as far back as 3.85 BYA
    • Maybe even 4.1 BYA
    • So what?
      • This means life arose considerably earlier than 3.85 BYA
        • ie. quite early in Earth’s history, as soon as conditions allowed, after the ‘late heavy bombardment’
        • If life arose through a simple natural process (as opposed to a lucky event), then life might be quite common in the universe.
      • Of course, the exact date of when life began is still a mystery…

Where

Genetic Evidence
  • Evolution works slowly
    • By mutation (random)
    • By natural selection (non-random)
  • Starting with the DNA of the Last Universal Common Ancestor of all life today, mutations slowly accumulate as species differentiate and bifurcate
  • Earth is constantly bombarded by high-energy particles, which potentially leads to mutations
    • Mutations are steady, and rates of mutation can be computed
  • Comparisons amongst the DNA of species alive today allows biologists to map evolutionary history
    • Two species with very similar DNA ==> more recent divergence
    • Two species with very different DNA ==> more ancient divergence
  • eg. plants and animals are actually quite similar (recently diverged)
  • Just as sharks branched off earlier than primates (as geological/fossil records confirm), some modern microbes are more closely related to the earliest organisms than others
  • Unfortunately, evidence regarding the nature of the organisms near the root of the tree is still not clear
    • Initially, they were thought to be extremophiles, like those living today near deep-sea hydrothermal vents, or deep underground
    • Recently, evidence emerged for non-extremophiles, like certain living archaea
Geological Evidence
  • Without exception, every life-form on Earth requires water. As such, it’s unlikely that life originated on land
    • Moreover, early atmosphere had no oxygen (O2), no ozone (O3)
      • No protection from the Sun’s intense UV
      • Life itself produces the atmosphere’s oxygen
  • Darwin’s Little Ponds?
    • Organic compounds can form spontaneously
    • The moon used to be a lot closer, hence higher tides
    • Tides, along with wetting/evaporation, would increase the concentration of these organic compounds
    • Perhaps volcanic hot springs offered the energy to support an origin of life?
    • Problem
      • Not much protection from UV
  • Deep-sea vents or underground
    • Provides protection from the Sun’s UV
    • Plenty of chemical energy to fuel reactions that may have led to life
      • for underground hypothesis: reactions between water & minerals in rock
    • Even if life arose in Darwin’s Ponds, lunar evidence of asteroid/comet impacts of the ‘late heavy bombardment’ suggests life would probably have been destroyed if it didn’t migrate into the deep-sea

How?

Life is very complex chemistry, and more

Amino acids are the building blocks of life

  • More than 100 amino acids occur in bacteria and plants, but only about 20 are commonly found in animals
  • 12 can be synthesized by the human body
    • The remaining 8 must come from our diet, the essential amino acids
  • Amino acids make up proteins, the second-largest component of human muscles, cells, and other tissues
    • Water is the largest

Proteins are long chains of animo acids, folded up in a complicated 3D structure, both of which determine the protein’s function

  • Catalyzing metabolic reactions (enzymes)
  • DNA recplication
    • Very complex process, and proteins help
    • More than a dozen enzymes are involved in unzipping the DNA, checking an correcting errors, and re-zipping the duplicated DNA
  • Transporting molecules around

Typical example of an enzyme (hexokinase), involved in catalyzing the conversion of glucose to glucose 6-phosphate via ATP

  • Basically the same molecule, with some phosphate attached
  • Hexokinase enzymes have little pockets, which helps connect molecules together
Initial puzzles
  • At the very least, life requires
    • Amino acids
      • Where do these come from?
    • Time
      • For interesting things to happen
  • Then, we can start to think about how simple organic compounds gave rise, over time, to complex and replicating life
    • Having notes is not the same as having music
Early Earth

Age of the Earth & Concept of “Deep Time”

  • Theology
    • A few thousand years to infinite, or cyclical
    • Commonly 5000-10000 years
    • Our thinking is limit to thousands of years, with age(s) of empires, cities, generations, etc
  • Starting in 1700s, rock erosion, sedimentation, and salt in the oceans suggest 10-100 million
    • How long would it take for natural wind and water erosion to carve a canyon?
    • Sediments in the ocean that have risen up (like the Cliffs of Dover)
      • What’s the sedimentation rate per year? Based on such, must be more than “thousands” of years
  • 1856, Helmholtz: Assumed that the Sun’s energy came from gravitational collapse
    • Suggests 22 million years, but is too small because it ignored the Sun’s real energy source: fusion
  • 1862, Lord Kelvin
    • Cooling of initially molten Earth –> 20-400 million
    • Still too small, as it ignored heating due to radioactivity of the rocks
      • Which will generally keep the rocks heated for longer
  • By later 1800s, geologists & evolutionists aruged for much (much) older –> billions –> bitter disputes
    • Preface in the first version of On Origin of Species was removed by Lord Kelvin
  • 1904, Ernest Rutherford
    • Realized radioactivity could heat the Earth
    • ie. Age could be much greater than Kelvin’s 1897 revised estimate of 20 million
    • Took first step towards radiometric dating of the Earth
  • 1924, Arthur Holmes
    • The Age of the Earth, and Introduction of Geological Ideas suggests/finds 1.6-3.0 billion years
Early Earth
  • Today, we know Earth is 4.54 +- 0.05 BYO
  • Radiometric dating (eg. Potassium-40 and Argon-40) of meteorites left over from Solar System formation –> 4.567 BYO
  • …consistent with radiometric dating of oldest Earth rocks (zircon crystals in Australia) –> 4.404 BYO
  • …consistent with radiometric dating of the oldest Apollo Moon rocks
  • …consistent with comparing the mass and luminosity of the Sun to those of other stars
    • Stars gradually brighten
  • The Sun formed from the gravitational collapse of a small part of a giant molecular cloud (H + He + heavier elements aka. “dust”, ie. “stardust”);
    • The Earth formed in a few million years by electrostatic then gravitational accretion of dust into grains –> clumps of grains –> planetesimals (~10 KM) –> high gravitation pull –> absorbs debris into a planet sized ball

Initially, the Earth had no oceans or atmosphere

  • Made from rocky/metallic planetesimals (icy planetesimals formed further out from the Sun)
  • Too small & warm to hold onto Hydrogen or Helium gasses, and too little other gasses around

Current models suggest

  • Rocky/icy plenetsimals far from Sun later flung inward by gravitation encounters
  • Trapped water and gas in this rock was later outgassed by volcanos (when Earth cooled)
    • Water vapor condensed to form oceans
    • Gasses (main CO2; also N2, H2S, SO2, H2) formed early atmosphere

Zircon evidence suggests Earth possibly had continents, oceans, and atmopshere as soon as 100 million years after the planet first formed

  • U-Pb dating –> solid zircon 4.4 BYA
  • Oxygen isotopes –> solidified in presence of water
  • Radioactive rocks, or impact that made Moon –> Accelerated heating –> Outgassing?
  • Note: Life arose in a nearly oxygen-free environment
    • O2 is highly reactive
      • Prevents complex organic molecules forming outside cells
    • Life as we known it could not form in the present environment on Earth
      • Oxygen is too volatile: it oxydizes(?), etc
    • Oxygen only came after photo-synthesis and other life-forms began synthesizing it
Origin of Organic Molecules

Famous Miller-Urey experiment

  • Assumed (wrongly) that early Earth atmosphere was methane and ammonia, and energy driving chemical reations was lightning
  • Readily synthesized amino acids and other organic molecules
    • Amino acids can be easily created
  • Similar experiments today…
    • Problem: don’ know exact composition of the early atmosphere, especially H2 content

Other sources

  • Chemical reactions between water and minerals near deep-sea vents
  • Material from space
    • Asteroids & comets, UV from Sun acting on dust in solar nebula
Chemistry –> Biology?

Nobody thinks organic molecules just “popped up”

  • Plenty of organic molecules around, but how do they form living/replicating cells?
  • Random chance is virtually impossible
    • There must be a natural mechanism, but what?
  • Looking for high probability “chemical pathways”…
Chicken & Egg Paradox 1

Ribonucleic Acid (RNA, single-helix) Deoxyribonucleic Acid (DNA, double-helix)

Modern DNA cannot replicate without catalysing proteins, and enzymes cannot be made without DNA.

  • Which came first?
    • Possible solution: 1980s (Thomas Cech and colleagues—Nobel prize 1989)
    • RNA itself can catalyse many cellular biochemical reactions including (partially) their own replication
    • This supports the idea of an earlier “RNA World”, where RNA serves as both genetic and catalysing molecule
RNA World

Experiment

  • Inorganic minerals (a kind of “clay”) can facilitate self-assembly of RNA strands
  • Quickly and easily produces RNA stranges up to a few dozen bases in length
    • Note, zircon grain analysis suggests “clay” was widespread 4.4 BYA)
    • These RNA bases adhere to “clay” and essentially combine
  • However, need length > 165 bases for RNA to be able to catalyse its own replication
  • Short strands easily peel away from the clay & fold in ways that promote joining
  • Strands as small as 5 bases are able to catalyse various chemical reactions… like joining short strands into longer strands
  • Given the countless clay grinds, and that the RNA enzyme for joining is very simple, it is not unreasonable to expect very long RNA strands to form naturally (spontaneously)
  • This natural mechanism for creating longer RNA strands would have dramatically increased the chance of getting an RNA molecule long enough to self-replicate
    • Once this happens, growth is exponential
Chicken & Egg Paradox 2

Which came first, the cell membrane or its contents (genes and proteins)?

  • Sciences have known for decades that cooling a warm-water solution of amino acids can cause them to bond, forming a spherical shell “pre-cell”. Lipids (fats) in water also form pre-cells on the surface of the same clay minrals that assemble RNA molecules
    • Some pre-cell membrances exhibit real cell-membrance behaviours, like
      • Selective molecule transport across the membrane
      • Electrostatic energy storage and discharge
      • Growth and splitting into “daughter” spheres
  • [Slide 34]
RNA World –> DNA World

Gradually, these RNA organisms would have become “alive,” or “biological”, in the sense we think of now

  • Biological natural selection could then take over, resulting eventually in a DNA World
    • Similarity between RNA & DNA
    • DNA is more durable as a hereditary material
    • DNA is less prone to copying errors
  • RNA also served other functions in the cell, and so would stay, with now DNA serving the hereditary role

Summary

We still don’t know how life started, and probably will never know

  • Research continues (TODO FIX LINK)
    • ...a pair of simple compounds (HCN—Hydrogen Cyanid & H2S—Hydrogen Sulfide), which would have been abundant on early Earth, can give rise to a network of simple reactions that produce the three major classes of biomolecules—nucleic acids, amino acids, and lipids.
      • If true, it might solve both chicken/egg paradoxes
  • We have constructed one plausible model (RNA World), backed up at many points by experiments, and scientists are working on others
Main Point

The origin of life seems like a plausible/likely consequence of conditions on early Earth and the laws of nature

  • Chemistry –> Biology
  • It wasn’t luck. It was probably bound to happen eventually
  • But is life a necessary consequence of the laws of nature at the most elementary level, ie. physics?

Life - Physics (Energy)

Living organisms must eat to sustain themselves. Why?

  • Something to do with “we are what we eat”
    • We get building blocks like amino acids
  • Also, for calories: we get energy
  • Energy in always equals energy out, although in different methods
    • How does that energy go through our system?
      • We take high-ordered energy, and release low-order energy

In exploring the origin of life, it helps to better understand what life is.

  • We will see that energy (the flow of energy and dispersion) is central to this understanding
  • First, the concept of energy and the principle of conservation of energy are central to all of science, and so worthwhile to explore

Potential Energy

  • When a ball collides elastically with a wall, it momentarily comes to rest, and so has no kinetic energy
  • However, its shape is distorted like compressed spring
    • It “springs back” to its original shape and restores the ball’s original kinetic energy
    • As it’s compressed/compressing, its kinetic energy is low
      • An object consists of more than simple kinetic energy
      • In this case, the original kinetic energy is converted or stored in another form/somewhere else
  • Atoms are made of electrically charged particles
    • A pos-charged nucleus and neg-charged electrons
    • Each charged particle is surrounded by an electric field, E
  • The electric fields of two or more charged particles add to produce a net electric field in the space around the particles

An electric field

  • Stores energy in the space between charged particles, with energy density = (1/2) * |E|^2 (joules per cubic metre)

The electric field energy stored between two metal plates.

  • This can be converted into kinetic energy (in this case, a 3.2 kg projectile moving at Mach 7)
    • This is a rail gun
  • This may also spark the release of more energy (via nuclear fusion) through the Z-pinch effect
    • Z-Machine at Sandia National Labs
    • Parallel charged wires will attract each other, and “pinch” at a point
      • There’s material inside the “tube” of wires, and the compression force is enough to cause nuclear fusion (?)

Energy can also be stored in a magnetic field, B, with energy density = (1/2) * |B|^2

  • As the sun rotates, it twists its magnetic field, which can snap and cause solar flares
    • A solar flare converts magnetic field energy into kinetic energy (up to ~10^25 J) or billions of the most powerful nuclear bombs human have built
    • Planets with liquid space need to be in “close” vicinity to red dwarves, which leaves it vulnerable to death-by-flare

Light is an electromagnetic field

  • Faraday
    • A changing magnetic field creates an electric field
  • Maxwell
    • A changing electric field creates a magnetic field

These two mechanisms work together to create light

  • A mutually self-sustaining, changing pattern of electric and magnetic fields in space
  • Light is potential energy stored in electric and magnetic fields, being transported through a vacuum at 300,000,0000 m/s

Gravitational Potential Energy

Tremendous amount of gravitational potential energy when an object is far away.

  • As the object moves closes, kinetic energy accumulates and the object becomes faster, while gravitation potential energy decreases
  • This provided the spark that ignited the Sun’s thermonuclear fusion reactions, which now provide virtually all energy for life on Earth

Thermal Energy

When a ball bounces elastically, the energy converts back and forth between kinetic and potential (gravitational & electric field) energy

  • Total energy is being conserved, but total kinetic energy becomes less and less
  • When the ball is inelastic, it seems as if the energy is disappearing
    • It’s not disappearing, it’s just that the kinetic energy is being converted into another form
  • What does the collision on the ground do to the kinetic energy in the ball?
    • Initially, all the particles in the ball are moving in the same direction (a bunch of arrows pointing in the same direction)
      • We say their KE is coherent and ordered
    • Collisions, however, randomize the kinetic energy (arrows now point in random directions)
    • With each collision, these atoms are given energy but they go in random directions
      • Each collision increases the disordered KE in the ball
      • And decreased the ordered KE in the ball
        • Kinetic energy is still the same
      • If the arrows could magically be rearranged to point in the same direction, it would start moving that way
    • Finally, the particles in the ball have no more ordered KE (the ball, as a whole, has no motion)
      • The particles in the ground near the ball have acquired more disordered KE
  • The Industrial Revolution is based on our ability to rearrange these arrows somehow
    • Not directly, but “generating” ordered kinetic energy was key

More correctly, thermal energy is the total energy associated with the thermal motion of a system of particles, including both kinetic and potential (field) energies

  • In the case of gases, the potential (field) energies are negligible, and the thermal energy is in the form of the disordered kinetic energy of the gas particles

Humans eat ordered energy and release disordered energy in equal quantity.

Einstein on Energy

E = mc^2

  • Energy is equivalent to mass
    • We’re not sure what either is, but at least the mysteries were reduced from 2 to 1
  • Objects resist change in motion
    • The more “massive,” the more resistant it is to change in motion
    • Mass is the resistance of an object to changes in its motion
      • As such, another name for mass is inertia

All forms of energy have mass (or inertia; resistance to acceleration)

Kinetic energy has mass

Heating the gas in a box (adding KE) makes it harder to accelerate the box * The box now has more mass, although we didn’t “add” any new particles * How much energy did we add with the flame? * deltaMass = deltaEnergy / c^2 * This number is exceedingly small, virtually unrecognizable, because c is so large

Potential energy has mass

Compressed springs weigh more. Not much more, but it has been measured

Thermal energy has mass

A hot cup of cofee (more kinetic and potential energy) is harder to get moving

  • It will weigh more on a very precise scale
  • Not noticeable to humans

Electromagnetic energy has mass

  • A mirror box full of light is harder to accelerate than the same box but empty
  • Even something like light adds mass

What does E=mc^2 mean?

Turning it around… then m=E/c^2

  • Mass itself has energy
  • An electon and positron (electron’s anti-matter cousin) both have the same “rest mass.”
    • They can annihilate each other, leaving an equivalent amount of mass-energy in the form of light
    • The total mass does not change. The total energy does not change
      • Mass is not converted into energy, nor vice versa
      • It’s just 20th century alchemy
        • One type of matter (electrons) is converted into another (photons)
  • Conversation of energy and conservation of mass are the same law
    • Because energy and mass are equivalent

Life is profoudly physical

Life - Physics (Entrophy)

Brownian Motion

  • Lucretius (c. 60 BC), On the Nature of Things: used the random motion of dust motes in a shaft of sunlight as evidence for Democritus’ idea of atoms
    • Essentially correct
  • Named after the botanist Robert Brown who, in 1827, observed similar random motion of pollen grains in water
    • Suggests the existence of atoms and molecules, which “push” these grains and dust motes around, producing their seemingly random motion
  • Mathematical descriptions began in the late 1800s
    • Einstein (1905) made a detailed quantitative analysis of Brownian motion that provided definitive confirmation that atoms and molecules actually exist

Diffusion

The net migration of particles from a region of high concentration to a region of low concentration

  • This is the process that animates life
  • Diffusion is similar to Brownian motion
    • Each particle moves independently, …
  • Continues until there is an equal concentration of particles in all layers –> equal number randomly moving right or left through any area A
  • Dynamic equilibrium

Nature has no inherent preference for one state ove another. There are simply many more ways for the particles to be spread out than they are to be localized

  • Even a tiny amount of spreading opens a vast increase in number of nearby states like this, compared to the less spread out state it come from
  • The system could go back, but by the law of large numbers, it will spend virtually all of its time “lost” in the huge new space nearby, more spread out states
  • This continues until equilibrium
    • There are stupendously more uniform-like states than even the slightly less uniform-like states a moment before
    • The system inexorably ratchets towards equilibrum
      • Every step it takes to becoming more spread out, it can still go back, but there are so few states that are more concentrated and so many states that are less concentrated
  • Again, there’s no reason the system can’t go back to its original state
    • It’s merely extremely unlikely
    • Basically, this process is irreversible

There are no physical laws that govern this process. It is driven one way (and not the other) by purely random, purposeless thermal motion.

  • Of all possible next states (of which nature prefers none), the vast majority are more spread out, so chances are the next state will be of a more spread out variation
  • Same for a coffee cup. There are stupendously more ways for thermal energy to spread uniformly throughout the room than to spread throughout the coffee alone
  • There is nothing preventing the thermal energy from flowing from the warmed air back into the room-temperature coffee
    • It’s just too unlikely

Second Law of Thermodynamics

**The entropy of an isolated system never decreases

  • The most potent statement in all of science
  • Roughly speaking, entropy is a measure of disorder. The natural diffusion or dispersion of energy (or particles) increases disorder in the universe
    • This happens naturally and spontaneously
    • But, this occurs at the expense of greater increase in disorder elsewhere
    • So, the universe as a whole (or any isolated system in the universe) inexorably ratchts towards greater disorder, or higher entropy
  • While energy is conserved, it is continually being degraded into lower quality energy.
    • Recall heat death
    • Still, it is precisely this lawless, purposeless process that is responsible for virtuall all change in the world
    • It is the engine of life itself

Entropy

First understood in the context of flow of thermal energy from a hot object to a cold object

Q = amount of thermal energy transferred Let S denote the entropy in the system

deltaS = Sf - Si = Q / T

deltaS_hot = -Q / T_hot < 0 --> entroy of hot object decreases
deltaS_cold = Q / T_cold > 0 --> entropy of cold object increases

Consider deltaS = deltaS_hot + deltaS_cold
then,
T_hot > T_cold ==> deltaS > 0
  • Entropy of cold object increases more than entropy of hot object decreases
    • Thus, we have a net increase

Kind of suggests that life is locked out of the past. Things happen towards higher entropy due to the overwhelmingly high odds of it happening. Conversely, things don’t do “backwards” because it’s far too unlikely.

However, there are other ways entropy can increase

  • When particles disperse, entropy also increases
    • There are stupendously more ways for particles to uniformly fill a volume than to occupy one corner
      • S = k * logW applies here also
  • When structural order decreases, entropy also increases
    • Converly, when structure order increases, entropy decreases
    • There are stupendously more ways for particles to be structurally disordered than ordered
      • S = k * logW applies here too
        • How many ways can water molecules be distributed in a waterdrop and still look like water?
          • Increased entropy
        • How about ice? Solids have more strict structures, and thus fewer possible structures
          • Reduced entropy
Summary

Boltzmann’s formula S = k * logW quantitatively enumerates disorder in all of its forms

  • The universality of this connection between macroscopic and microscopic worlds is why this formula is so important and far-reaching

Life and the Second Law

  • Living organisms exhibit a very high degree of order or complexity
    • How do they maintain this order against the tendency towards universal decay into disorder?
      • Does life not violate the Second Law?
    • What about evolution (to organisms of ever higher order or complexity)?
      • Surely this violates the Second Law?
        • No: The universal ratcheting…
Example

A freezer can convert water at 0C to ice at 0C

  • Ice is a more ordered structure than water, so changing water to ice reduces the entropy of the H2O
  • The water-to-ice transition releases energy (“latent heat”) because H2O bonds in ice are more stable (stronger/lower energy) than H2O bonds in water
    • The freezer removes this energy and dumps it into the environment
    • The resulting entropy increase (energy spreading) exceeds the water-to-ice decrease
      • Hence, net entropy is positive (increase)
  • A freezer does not violate the Second Law
  • High quality energy in the form of electricity come into the freezer
  • The food/contents of the freezer “consume” the energy, converting it into low quality (high entropy) energy
Order from Disorder

Recall the natural flow from order to disorder. While a ball falls, it has kinetic energy. It is very ordered: all of the particles have motion in the same direction (high degree of order)

  • After a few bounces, the order has become disorderd. Motion in particles are now in different directions

Question

Can we build a machine that re-orders the energy?

  • Of course, consider a car engine (a piston engine).
  • Consider a simple gasoline engine
    • We have a cylinder, with a hot source at the top and a cold sink at the bottom
      • Naturally, thermal energy spontaenously flows from the source to the sink
      • But, this isn’t too useful
    • What if we put some machine between the natural flow?
~~~~~~~
|HHHHH|
|     |
| v ~~~~~~~~
| v |		-->
| v ~~~~~~~~
|     |
|CCCCC|
~~~~~~~
  • As gas is heated near the source, thermal energy moves towards the sink
  • As it travels through the cylinder, hot gas atoms bombard the piston. This causes it to move in the only directly possible
    • We extract high-ordered energy (in ordered kinetic motion) from disordered thermal energy
Big Picture

This coherent kinetic energy can be used to move people (cars, planes, etc), build structures (bridges, cathedrals), and do a myriad of other constructive scenes

  • The universe’s inexorable slide into chaos can be harnessed for construction of order
    • As long as it is accompanied by greater destruction of order elsewhere
  • However, it requires a complex machine
    • Early on, humans mastered burning fuels to create heat (wood, coal, oil –> fires, steam engines, etc)
      • Trapped energy from the Sun, then uranium for fission, soon hydrogen for fusion
      • Energy from the Big Bang
    • We only recently figured out how to burn fuels to produce work
      • This sparked the industrial revolution
So What?

Thinking about it, a human is at least just such a complex machine.

  • We take low entropy material containing high-quality energy: food-fuel
  • We burn this food-fuel and expel waste high-entropy material / low-quality energy
  • In the process, it constructs low-entropy energy
  • Once we have the machine, we just need to feed it and it will function spontaneously
  • What animates living organisms is simply the spontaneous, puposeless, dispersion of energy (& particles) from more ordered to less ordered forms
    • A human is a machine that harnesses…