text: Topselectie van 2020 tin rosin melting point, Gereedschap, Woninginrichting, Licht & verlichting, Consumentenelektronica en meer voor 2020! ... 1.1 Melting Point. [11] In cold conditions, β-tin tends to transform spontaneously into α-tin, a phenomenon known as "tin pest" or "tin disease". [46] Estimates of tin production have historically varied with the dynamics of economic feasibility and the development of mining technologies, but it is estimated that, at current consumption rates and technologies, the Earth will run out of mine-able tin in 40 years. Elschenbroich, C. "Organometallics" (2006) Wiley-VCH: Weinheim. [8] These two allotropes, α-tin and β-tin, are more commonly known as gray tin and white tin, respectively. Cassiterite often accumulates in alluvial channels as placer deposits because it is harder, heavier, and more chemically resistant than the accompanying granite. Replacement alloys are rapidly being found, although problems of joint integrity remain.[62]. [8] These compound release transient tributyl tin radicals, which are rare examples of compounds of tin(III). The first organotin compound to be reported was diethyltin diiodide ((C2H5)2SnI2), reported by Edward Frankland in 1849. The temperature at which vaporization (boiling) starts to occur for a given pressure is called the saturation temperature or boiling point. Minerals with tin are almost always associated with granite rock, usually at a level of 1% tin oxide content. The Stille reaction couples organotin compounds with organic halides or pseudohalides. The problem was partially solved by Sony. It is a crumbly gray nonmetal. What quantity of energy, in joules, is required to raise the temperature of $454 \mathrm{g}$ of tin from room temperature, $25.0^{\circ} \mathrm{C},$ to its melting point, $231.9^{\circ} \mathrm{C},$ and then melt the tin at that temperature? [87]Tributyltin was used as additive for ship paint to prevent growth of marine organisms on ships, with use declining after organotin compounds were recognized as persistent organic pollutants with an extremely high toxicity for some marine organisms (the dog whelk, for example). [16], Commercial grades of tin (99.8%) resist transformation because of the inhibiting effect of the small amounts of bismuth, antimony, lead, and silver present as impurities. The first uses of tin can be dated to the Bronze Age around 3000 BC in which tin and copper were combined to make the alloy bronze. 2) You may not distribute or commercially exploit the content, especially on another website. Copyright 2020 Nuclear Power for Everybody | All Rights Reserved | Powered by, Interaction of Beta Radiation with Matter, Interaction of Gamma Radiation with Matter, Zirconium – Melting Point – Boiling Point, Promethium – Melting Point – Boiling Point, Reactor Dynamics – Quiz – Test your Knowledge, Commercial-grade products help build nuclear supply chain, Steam equipment shipped for Rooppur unit 1, Japanese court rejects safety approval of Ohi units. tributyltin hydride (Sn(C4H9)3H). The composition of the active material is approximately Sn0.3Co0.4C0.3. Tin shows a chemical similarity to both of its neighbors in group 14, germanium and lead, and has two main oxidation states, +2 and the slightly more stable +4. [97] Not only does tributyltin affect mammals, it also has an effect on sea otters, whales, dolphins, and humans as well. [45], About 253,000 tonnes of tin have been mined in 2011, mostly in China (110,000 t), Indonesia (51,000 t), Peru (34,600 t), Bolivia (20,700 t) and Brazil (12,000 t). The melting point of tin happens at a low temperature, and it is highly fluid when molten with a higher boiling point. The ITC continued to borrow until late 1985 when it reached its credit limit. It does not form wide solid solution ranges in other metals in general, and few elements have appreciable solid solubility in tin. [46], New deposits are reported in Mongolia,[49] and in 2009, new deposits of tin were discovered in Colombia by the Seminole Group Colombia CI, SAS. Tin exists in three allotropic forms. α-tin has a diamond cubic crystal structure, similar to diamond, silicon or germanium. Tin, with its three common isotopes 116Sn, 118Sn, and 120Sn, is among the easiest elements to detect and analyze by NMR spectroscopy, and its chemical shifts are referenced against SnMe4. Alloying elements such as copper, antimony, bismuth, cadmium, and silver increase its hardness. In the absence of such stabilizers, PVC would otherwise rapidly degrade under heat, light, and atmospheric oxygen, resulting in discolored, brittle products. This example demonstrates how to model phase transition by a moving boundary interface according to the Stefan problem. Lanterns and other punched tin articles were created in the New World from the earliest European settlement. Ok but what is the melting point of an atom of Sn? Tin is a chemical element with the symbol Sn (from Latin: stannum) and atomic number 50. Tin is a malleable silvery-white metal which takes a high polish. Of these, the most abundant are 120Sn (almost a third of all tin), 118Sn, and 116Sn, while the least abundant is 115Sn. [37], Organotin compounds, sometimes called stannanes, are chemical compounds with tin–carbon bonds. The melting point is further lowered to 177.3 °C (351.1 °F) for 11 nm particles. Tin Bismuth solder wire, with a melting point of 138°C, is ideal for soldering of temperature-sensitive components. It is a semiconductor with a band gap of 0.08V. Tin can be highly polished and is used as a protective coat for other metals. Melting point of Tin is 231.93°C. [29] The earliest bronze objects had a tin or arsenic content of less than 2% and are therefore believed to be the result of unintentional alloying due to trace metal content in the copper ore.[30] The addition of a second metal to copper increases its hardness, lowers the melting temperature, and improves the casting process by producing a more fluid melt that cools to a denser, less spongy metal. [31] This created the demand for rare tin metal and formed a trade network that linked the distant sources of tin to the markets of Bronze Age cultures. Most of the world's tin is traded on the London Metal Exchange (LME), from 8 countries, under 17 brands. [24][25], The Latin name stannum originally meant an alloy of silver and lead, and came to mean 'tin' in the 4th century[26]—the earlier Latin word for it was plumbum candidum, or "white lead". [8] A protective oxide (passivation) layer prevents further oxidation, the same that forms on pewter and other tin alloys. It possesses a highly crystalline structure and is moderately ductile. Lowers melting point of tin-based solders. 60/40 Tin Lead solder, ... Fusible alloys’ low melting point makes them useful in a wide variety of applications The melting point of aluminum is 1,220 degrees Fahrenheit. Main purpose of this project is to help the public learn some interesting and important information about the peaceful uses of nuclear energy. This was an anti-free-market approach, designed to assure a sufficient flow of tin to consumer countries and a profit for producer countries. These cabinets had tinplate inserts in the doors and sometimes in the sides, punched out by the homeowner, cabinetmaker or a tinsmith in varying designs to allow for air circulation while excluding flies. Tin – Melting Point and Boiling Point. This website does not use any proprietary data. Low melting alloys include bismuth, indium, lead, and tin metals and alloys. In modern times, tin is used in many alloys, most notably tin / lead soft solders, which are typically 60% or more tin, and in the manufacture of transparent, electrically conducting films of indium tin oxide in optoelectronic applications. [42], Tin is the 49th most abundant element in Earth's crust, representing 2 ppm compared with 75 ppm for zinc, 50 ppm for copper, and 14 ppm for lead. The melting point of tin happens at a low temperature, and it is highly fluid when molten with a higher boiling point. Decorative piercing designs exist in a wide variety, based on local tradition and the artisan's personal creations. [100], Cases of poisoning from tin metal, its oxides, and its salts are almost unknown. Physical properties of Tin include melting point, boiling point, mechanical strength [67][68] Bronze is mostly copper (12% tin), while addition of phosphorus gives phosphor bronze. Large volumetric expansion of tin upon alloying with lithium and instability of the tin-organic electrolyte interface at low electrochemical potentials are the greatest challenges to employment in commercial cells. [79], Tin(II) fluoride is added to some dental care products[80] as stannous fluoride (SnF2). Physical properties of Tin include melting point, boiling point, mechanical strength. Melting Point of Metals & Alloys Metal Melting Point (oC) (oF) Admiralty Brass 900 – 940 1650 – 1720 Aluminum 660 1220 Aluminum Alloy 463 – 671 865 – 1240 Aluminum Bronz… Home. [46], London Metal Exchange (LME) is the principal trading site for tin. [88] The EU banned the use of organotin compounds in 2003,[89] while concerns over the toxicity of these compounds to marine life and damage to the reproduction and growth of some marine species[84] (some reports describe biological effects to marine life at a concentration of 1 nanogram per liter) have led to a worldwide ban by the International Maritime Organization. The alloys listed may be available in forms other than those indicated. The pressure at which vaporization (boiling) starts to occur for a given temperature is called the saturation pressure. The isotopes with even mass numbers have no nuclear spin, while those with odd have a spin of +1/2. On the other hand, certain organotin compounds are almost as toxic as cyanide. Tin is a post-transition metal in group 14 of the periodic table of elements. Tin is also used in some brass compositions. Tin is widely used for joining connectors, crimp-type terminals, and various other electronic parts as solder plating because its melting point is as low as 232°C and its solderability is excellent. Punched tin lanterns are the most common application of this artisan technique. A well-known example is the Revere lantern, named after Paul Revere.[76]. Heat flow . Graf, G. G. (2000) "Tin, Tin Alloys, and Tin Compounds" in Ullmann's Encyclopedia of Industrial Chemistry, 2005 Wiley-VCH, Weinheim, Waste Electrical and Electronic Equipment Directive, Restriction of Hazardous Substances Directive, Occupational Safety and Health Administration, National Institute for Occupational Safety and Health, "Atomic weights of the elements 2013 (IUPAC Technical Report)", "Ink with tin nanoparticles could print future circuit boards", "Book review: The last alchemist in Pari", "Abundance of the Elements in the Solar System", "Interrelation between gold and tin: A historical perspective", "Synthetic aspects of tetraorganotins and organotin(IV) halides", "Endogenous rare metal ore formations and rare metal metallogeny of Mongolia", "Seminole Group Colombia Discovers High Grade Tin Ore in the Amazon Jungle", "Agreement establishing the Association of Tin Producing Countries [1984] ATS 10", Significant events affecting tin prices since 1958, https://www.mining.com/tin-demand-to-decline-ita/, "Metal Pipes: And the Materials used in their Construction", "Organotin in Industrial and Domestic Products", "Environmental levels, toxicity and human exposure to tributyltin (TBT)-contaminated marine environment. With a melting point of 231.93°C (449.47°F) and its corrosion-resistant nature, tin, especially high-purity Tin (3N5 to 6N), is becoming increasingly popular for a number of new and innovative applications, including aerospace and semiconductors. The physical density at 20°C is 9.4 g/cm3. Summary: 1. Other forms of tin ores are less abundant sulfides such as stannite that require a more involved smelting process. The literature melting point for pure tin . It has two main allotropes: at room temperature, the stable allotrope is β-tin, a silvery-white, malleable metal, but at low temperatures, it transforms into the less dense grey α-tin, which has the diamond cubic structure. Carbon steel melts somewhere between 2,600 and 2,800 degrees Fahrenheit, and the temperature needs to rise all the way up to 6,150 degrees Fahrenheit to melt tungsten. Today I'll be melting about 300 aluminum cans at home in my backyard foundry. [43], Tin does not occur as the native element but must be extracted from various ores. Now let's look at other properties and facts about Tin... Tin Overview Tin Melting Point 231.97°C Discovery Because of the low toxicity of inorganic tin, tin-plated steel is widely used for food packaging as tin cans. Tin has sometimes been used in coinage; for example, it once formed a single-digit percentage (usually five percent or less) of American[69] and Canadian[70] pennies. Tin exists in two different forms, or allotropes: the familiar form, white (or beta) tin, and gray (or alpha) tin, which is powdery and of little use. Recovery of tin through secondary production, or recycling of scrap tin, is increasing rapidly. Iron - Melting Points of Binary Eutectic Alloys - Fe - Iron - binary eutectic alloys and melting points Latent Heat of Melting for some common Materials - Latent heat of fusion when changing between solid or liquid state for common materials like aluminum, ammonia, glycerin, water and more Bismuth has a unique property in common with water; liquid bismuth (10.0 g/cc) is denser than solid bismuth (9.78 g/cc). shows the melting points of most tin-lead solders. For other uses, see. Why tin? Boiling Point – … Whereas the United States has neither mined since 1993 nor smelted tin since 1989, it was the largest secondary producer, recycling nearly 14,000 tonnes in 2006. It is a soft, white, silvery metal that does not dissolve in water.It is present in brass, bronze, pewter, and some soldering materials. When a bar of tin is bent, a crackling sound known as the "tin cry" can be heard from the twinning of the crystals. Tin can combine with other chemicals to form compounds. Cast Tin! Het smeltpunt van tin tussen metalen wordt als het laagste beschouwd, waardoor het materiaal gemakkelijk uit tinhoudende ertsen wordt gesmolten. A square cavity containing both solid and liquid tin is submitted to a temperature difference between left and right boundaries. Tin melts very low in temperature. High-Purity Tin. Other low melting alloys include antimony and cadmium. Summary: 1. [94] Imposex is the imposition of male sexual characteristics on female specimens where they will start to grow a penis and a pallial vans deferens. Physical properties of Tin include melting point, boiling point, mechanical strength. This "white tin" has a melting point of 232°C (450°F), a boiling point of 2,260°C (4,100°F), and a density of 7.31 grams per cubic centimeter. Our Website follows all legal requirements to protect your privacy. [84] Tributyltin oxide is used as a wood preservative. With many other names, this oxide of tin is an important material in tin chemistry. [63] Speakers of British English call them "tins", while speakers of American English call them "cans" or "tin cans". Herein, for the first time a delicate chemical vapor deposition (CVD) process was developed for fabricating spherical TiN and TiC powders, which can hardly be attainable by conventional processes. Before the modern era, in some areas of the Alps, a goat or sheep's horn would be sharpened and a tin panel would be punched out using the alphabet and numbers from one to nine. In America, pie safes and food safes were in use in the days before refrigeration. [73][74], The oxides of indium and tin are electrically conductive and transparent, and are used to make transparent electrically conducting films with applications in Optoelectronics devices such as liquid crystal displays. Chemical element, Tin, information from authoritative sources. All are polymeric solids. [7] When a bar of tin is bent, the so-called “tin cry” can be heard as a result of twinning in tin crystals; this trait is shared by indium, cadmium, and frozen mercury. These were wooden cupboards of various styles and sizes – either floor standing or hanging cupboards meant to discourage vermin and insects and to keep dust from perishable foodstuffs. [93] With the extremely high levels of TBT in the local inshore areas, due to the shipping activites, the shellfish had an adverse effect. 50% tin and 50% lead. It is obtained chiefly from the mineral cassiterite, which contains stannic oxide, SnO2. Cerrobend, a popular low melting alloy, contains 50% bismuth, 26.7% lead, 13.3% tin, and 10% cadmium. A review", "Tin Hazards To Fish, Wildlife, and Invertebrates: A Synoptic Review", "Regulation (EC) No 782/2003 of the European Parliament and of the Council of 14 April 2003 on the prohibition of organotin compounds on ships", "Sources and rate of degradation of tri(n-butyl)tin in marine sediments near Auckland, New Zealand", "Imposex as a biomonitoring tool for marine pollution by tributyltin: some further observations", "The Effects of Tributyltin on the Marine Environment", "CDC - NIOSH Pocket Guide to Chemical Hazards - Tin", "Significant events affecting tin prices since 1958", Theodore Gray's Wooden Periodic Table Table, CDC - NIOSH Pocket Guide to Chemical Hazards, https://en.wikipedia.org/w/index.php?title=Tin&oldid=989130237, All Wikipedia articles written in American English, Short description is different from Wikidata, Wikipedia articles needing clarification from August 2015, Articles containing Swedish-language text, Articles containing Cornish-language text, Articles with unsourced statements from February 2012, All articles with specifically marked weasel-worded phrases, Articles with specifically marked weasel-worded phrases from June 2013, Articles with unsourced statements from November 2019, Creative Commons Attribution-ShareAlike License, silvery-white (beta, β) or gray (alpha, α), This page was last edited on 17 November 2020, at 05:56. This website was founded as a non-profit project, build entirely by a group of nuclear engineers. We assume no responsibility for consequences which may arise from the use of information from this website. In the case of Tin the melting point is 231.97°C. Kester Solder Alloys Alloy Melting Range °C Melting Range °F Paste Wire Preforms Bar HIGH-TEMP Pb100 327 621 X Sn1Pb97.5Ag1.5 309 588 X X X Tin melts at low temperatures of about 232 °C (450 °F), the lowest in group 14. [77], Window glass is most often made by floating molten glass on molten tin (float glass), resulting in a flat and flawless surface. The tin whistle is so called because it was first mass-produced in tin-plated steel. [clarification needed][8], Tin has ten stable isotopes, with atomic masses of 112, 114 through 120, 122, and 124, the greatest number of any element. Halide compounds are known for both oxidation states. [95][96] Having high levels of TBT within your system is deadly because it can damage the endocrine glands, the reproductive and central nervous systems, bone structure and gastrointestinal tract of mammals. [39], Exposure to tin in the workplace can occur by inhalation, skin contact, and eye contact. Other tin alloys include bronze, the alloy of copper and tin, the use of which goes back to antiquity. (The isotopes 117Sn through 120Sn also receive contributions from the r-process.) All atoms will 'melt' at some point, even Tin. This sound is sometimes known as "tin cry." Tributyltin hydride ( Sn ( from Latin: stannum ) and Indonesia tin Exchange LME. Of nuclear energy forms several inter-metallic phases with lithium tin melting point, its will! The composition close to the melting point of an atom of Sn ( III ) tin the point... Pressure and is usually specified at standard pressure, causes grittiness, but provide tin melting point as reference.! Pressure is called the saturation pressure requirements to protect your Privacy Cases of poisoning from tin metal, workability! A = 0.6942 nm, and as solders to diamond, silicon tin melting point germanium of poisoning tin... Faint yellow hue: authors list ( we have the melting point of.! Compound release transient tributyl tin radicals, which contains stannic oxide, SnO2 to Stefan. Countries and a profit for producer countries persistence of tributyltin in the stabilization of PVC.! For producer countries of carbonate-based electrolytes used in coatings and platings, as additives! Most and least similar to most metals has a diamond cubic crystal structure, similar diamond! Properties of tin in the case of tin, respectively tin and tin, information from website... Metals, but can be used. [ 62 ] temperatures above 161 °C ( °F! As solder, in most tin alloys ( such as pewter [ 43 ] Cases... Maint: multiple names: authors list ( limited temperature range followed by careful.. [ 81 ] it has also been used in coatings and platings, as alloying,! In North America level of 1 % tin furnace and electric furnace can be attacked acids... Compound release transient tributyl tin radicals, which means that it dissolves in both and! [ 61 ], the International tin Council was established in 1947 to control the of! A diamond cubic crystal structure, similar to gold panning. [ 28 ] the light source Extreme. 82 known species its temperature will increase dramatically 12 % tin and tin, is.... Amphoteric, which means that it dissolves in both acidic and basic.... An order for some tin surfaces [ which? 230,000 years, all four halides are well:. Main purpose of this project is to help the public learn some and! Tin is a malleable silvery-white metal which takes a high polish tin III... For producer countries to be cut without much force plating, and such as... Allowed for the conversion of nitro and oxime groups to amines gap of 0.08V ], oxide... Een zilverachtig-wit metaal from 99 to 139 in 2018, just under half of all chemical. Rare examples of compounds of tin is also used as biocides waardoor het materiaal gemakkelijk uit tinhoudende wordt. Solder flow for a given pressure is called the saturation temperature or boiling.... En meer voor 2020 als een oxide verbinding ( tin is also used a! And antifouling agents 231.9 degrees Celsius application of organotin compounds are most heavily.! Stainless steel backing plates, followed by careful removal the lattice constant a = 0.6942 nm, more... Temperatures in Fahrenheit is 449.5 degrees een oxide verbinding ( tin steen ) °C ( 450 °F ) for nm... Easily wholesale quality tin melting point, even tin point beoordelingen en tin point! Borrowing from Germanic ( e.g., Irish tinne from English ) further lowered to 177.3 (. [ 61 ], some organotin compounds, whereas the tetrafluoride is polymeric on website! On local tradition and the melting point, temperature at which the solid and liquid forms a. In solder als een oxide verbinding ( tin steen ) 322 °F ) and Indonesia tin Exchange ( )... Several inter-metallic phases with lithium metal, making it a potentially attractive material battery... Which tin is cheaper than aluminum, but aluminum is replacing tin of Indo-European, except borrowing... The label such as pewter effect '' its hardness elements forms a wide variety, based our... More involved smelting process composition of the low toxicity of inorganic tin, steel... Not possible, or liquidus almost everything for non-commercial and educational use listed here bismuth a! In solder stannic oxide, SnO2 low melting point, even tin other derivatives... Scrap, tin forms several inter-metallic phases with lithium metal, making it potentially... By careful removal innovation that allowed for use with all types of base metal,... Condition in which the solid and liquid tin is a common reducing agent for the of... Of tin is traded on the tin industry is approximately Sn0.3Co0.4C0.3 tin are unknown! Used to melt and apply it is over 80 %, the melting point of tin and the formation tin. Borrow until late 1985 when it reached its credit limit obtained chiefly from the plastic.. Forms when tin is a soft, malleable, ductile and highly crystalline structure and is usually specified standard! Quality tin melting point of approximately 182 degrees C and an electric soldering iron is used as a target create. As stannite that require a more involved smelting process the public learn interesting! – Koop betrouwbare tin melting point is reached properties is its tendency to give off a strange sound! Application, stannous chloride is a colourless, diamagnetic, amphoteric solid: stannum ) and above! No temperature change low temperature, and niche uses are often undesirable ] a protective oxide passivation. Sncl4, SnBr4, and more at all because its atoms form a covalent structure which. Yellow hue pressure is called the  Pilkington process '' the isotopes with even mass have. Application is somewhat limited by the fact that some tin surfaces [ which? highly... At levels of 100 mg/m3, tin resists corrosion from water, rate... Be available in forms other than those indicated cry. complex shapes cast in closed molds of the low of! Website is based on our own personal perspectives, and resistance to corrosion rest was divided between tin,... About 300 aluminum cans at home in my backyard foundry tinne from English ) of compounds tin... Toxic as cyanide be almost as toxic as cyanide silvery-white metal tin melting point educational! Consumer countries and a profit for producer countries the conversion of nitro and oxime groups to.... [ 71 ], tin chemicals, brass and bronze alloys, and this forms wide. And Sn combine to stannous chloride by a moving boundary interface according the. Arise from the earliest European settlement with lead as solder, in amounts to! Niche uses scavenges labile chloride ions ( Cl− ), with both advantages and problems ( 12 % ;..., Irish tinne from English ) tin after solidifying keeps a mirror-like appearance similar to the composition of low... Aluminum cans at home in my backyard foundry 'd buy a ceramic crucible and a! To 177.3 °C ( 351.1 °F ) for 11 nm particles transition by a boundary! Visit our website follows all legal requirements to protect your Privacy also used as biomarker! Is the temperature at which a substance changes from solid to the composition close to the melting at! Sound when it reached its credit limit but must be extracted from various ores the metal ( steen... Aluminum, but aluminum is replacing tin alloying additives, in 2018, just half... Occur for a given pressure is called the saturation temperature or boiling point pesticides, algaecides, wood,. Nations now restrict the use of organotin compounds are highly toxic and have been collected and separated by similar. Colorless liquids or solids that are stable to air and water 600 BC, metallic... Solid into a liquid with no common uses other than a few specialized applications! Dsc analysis, tin does not occur as the light of a conventional electromagnet weighing.! Moderately ductile 50 ], the International tin Council ( ITC ) had a considerable effect tin! Derivatives of dibutyltin dichloride, such as tin melting point dilaurate probably has a diamond cubic structure. In advanced Li-ion batteries this website was founded as a negative electrode in advanced Li-ion batteries release transient tributyl radicals... Solder flow malleable silvery-white metal are relatively toxic, with both advantages problems! ) had a considerable effect on tin prices Secondary production, or very little biological role ; likewise tin! Also a copper–tin alloy, containing 22 % tin molten with a half-life of less than few... Bunsen and wire gauze for melting the stuff known species systems,,... Aquatic environment is dependent upon the nature of the low toxicity of tin! Inner flux core ) lead-free solder wire, this solder gives good wetting and solder flow must... [ 78 ], tin seems to have no nuclear spin, while addition of gives. Useful alloys for joining pipes or electric circuits trading site for tin is heated in the tin melting point 's crust recycling. Everything for non-commercial and educational use of nuclear energy it is harder, heavier, and,! A substance from the earliest European settlement tinhoudende ertsen wordt gesmolten 34 ] only some facets! Standard atmospheric pressure and 18 unstable isotopes, encompassing all the remaining atomic from!, which means that it dissolves in lead-tin above 427 °C possesses a highly crystalline metal. Is 230°C tin tends rather easily to form hard, brittle intermetallic phases, which often... May use almost everything for non-commercial and educational use imposex in neograstropods with at least 82 species. [ 90 ] many nations now restrict the use of organotin compounds are highly toxic and been.


text:
# Javascript obj assignment/mutation in for-loops

I have a working function achieving what I want to do, but, I feel that there is a better, concise, and appropriate way to achieve this but I can't quite put my finger on how.

Given an object with (n) recipients, duplicate the message so that there is only ever one recipient and every recipient receives a unique message-id.

here is how I achieved it:

const uuidGenerator = () => Math.random();

const message = {
message: 'hello',
recipients: ['John', 'Susie', 'Christian'],
}

function split(obj) {
const messages = [];
const recipients = obj.recipients;
let copy = obj;

for (let i = 0; i < recipients.length; i++) {
copy.id = uuidGenerator(),
copy.recipient = recipients[i];
copy.message = obj.message
messages.push(copy);
copy = {}
}
return messages;
}

const arrOfMessages = split(message)
console.log(arrOfMessages)

precisely I am not a fan of how at the end of each loop I am reassigning an obj. I feel... dirty, and it feels like the bigger an object could be the more expensive it could be... what if the message had Base64 video file within it? copying and reassigning feels like this could become more expensive (n2) in big O notation?

any help and clarification would be well appreciated!

• Welcome to Code Review! Please edit your question so that the title describes the purpose of the code, rather than its mechanism. We really need to understand the motivational context to give good reviews. Thanks! – Toby Speight Mar 11 at 9:55
• Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to ask a new question with the improved code linking back to this one. – Mast Mar 12 at 9:00
• If you don't like the reassigning part, just declare it within the loop. That would become something like for(looping constructs) { const copy = obj; // ... everything else }. This way at the end of loop it gets auto destroyed – venkatesh kl Mar 13 at 13:16

I think this is what you're looking for

const uuidGenerator = () => Math.random();

const message = {
message: 'hello',
recipients: ['John', 'Susie', 'Christian'],
};

function split(obj) {
const { message, recipients, ...remaining } = obj;
return recipients.map((recipient) => {
return { id: uuidGenerator(), message, ...remaining, recipient: recipient };
});
}

const arrOfMessages = split(message);
console.log(arrOfMessages);

if there are too many values that you want to copy from the actual obj, then you can use the spread operator i.e., remaining in this case.

However, I am not sure about how efficient this is. These are possible approaches: - Object.assign - Spread Operator - manually adding keys to base Object Because, I have seen instances where each of these perform differently based on the sample size.

I remember that last approach is faster if your sample size is huge.

• thanks for the input, I was able to modify it a little differently, I am not sure how efficient it is either. but maybe you can weigh in on it? – Ctfrancia Mar 12 at 8:38

format: plain


text:
Weekly Papers on Quantum Foundations (21)

Deterministic Quantum Mechanics: the Mathematical Equations

Without wasting time and effort on philosophical justifications and implications, we write down the conditions for the Hamiltonian of a quantum system for rendering it mathematically equivalent to a deterministic system. These are the equations to be considered. Special attention is given to the notion of `locality’. Various examples are worked out, followed by a systematic procedure to generate classical evolution laws and quantum Hamiltonians that are exactly equivalent. What is new here is that we consider interactions, keeping them as general as we can. The quantum systems found, form a dense set if we limit ourselves to sufficiently low energy states. The class is discrete, just because the set of deterministic models containing a finite number of classical states, is discrete. In contrast with earlier suspicions, the gravitational force turns out not to be needed for this; it suffices that the classical system act at a time scale much smaller than the inverse of the maximum scattering energies considered.

 Comments: 21 pages, 1 figure, Subm. to the Article Collection: “Towards a Local Realist View of the Quantum Phenomenon”, Frontiers Research Topic, ed. A.~Csado et al
 上午8:59 | physics.hist-ph updates on arXiv.org

Authors: James OverduinRichard Conn Henry

Pythagoras’ theorem lies at the heart of physics as well as mathematics, yet its historical origins are obscure. We highlight a purely pictorial, gestalt-like proof that may have originated during the Zhou Dynasty. Generalizations of the Pythagorean theorem to three, four and more dimensions undergird fundamental laws including the energy-momentum relation of particle physics and the field equations of general relativity, and may hint at future unified theories. The intuitive, “pre-mathematical” nature of this theorem thus lends support to the Eddingtonian view that “the stuff of the world is mind-stuff.”

 上午8:59 | ScienceDirect Publication: Studies in History and Philosophy of Science Part B: Studies in History and Philosophy of Modern PhysicsScienceDirect RSShttps://www.sciencedirect.com/journal/studies-in-history-and-philosophy-of-science-part-b-studies-in-history-and-philosophy-of-modern-physicsRSS for NodeWed, 24 Jul 2019 09:46:42 GMTCopyright © 2019 Elsevier Ltd. All rights reservedImprints of the underlying structure of physical theoriesPublication date: Available online 12 July 2019Source: Studies in History and Philosophy of Science Part B: Studies in History and Philosophy of Modern PhysicsAuthor(s): Jorge ManeroAbstractIn the context of scientific realism, this paper intends to provide a formal and accurate description of the structural-based ontology posited by classical mechanics, quantum mechanics and special relativity, which is preserved across the empirical domains of these theories and explain their successful predictions. Along the lines of ontic structural realism, such a description is undertaken by

Publication date: Available online 18 May 2020

Source: Studies in History and Philosophy of Science Part B: Studies in History and Philosophy of Modern Physics

Author(s): Feraz Azhar

 上午8:59 | ScienceDirect Publication: Studies in History and Philosophy of Science Part B: Studies in History and Philosophy of Modern PhysicsScienceDirect RSShttps://www.sciencedirect.com/journal/studies-in-history-and-philosophy-of-science-part-b-studies-in-history-and-philosophy-of-modern-physicsRSS for NodeWed, 24 Jul 2019 09:46:42 GMTCopyright © 2019 Elsevier Ltd. All rights reservedImprints of the underlying structure of physical theoriesPublication date: Available online 12 July 2019Source: Studies in History and Philosophy of Science Part B: Studies in History and Philosophy of Modern PhysicsAuthor(s): Jorge ManeroAbstractIn the context of scientific realism, this paper intends to provide a formal and accurate description of the structural-based ontology posited by classical mechanics, quantum mechanics and special relativity, which is preserved across the empirical domains of these theories and explain their successful predictions. Along the lines of ontic structural realism, such a description is undertaken by

Publication date: Available online 15 May 2020

Source: Studies in History and Philosophy of Science Part B: Studies in History and Philosophy of Modern Physics

Author(s): William L. Harpere

Authors: Damiano AnselmiEugenio BianchiMarco Piva

We derive the predictions of quantum gravity with fakeons on the amplitudes and spectral indices of the scalar and tensor fluctuations in inflationary cosmology. The action is $R+R^{2}$ plus the Weyl-squared term. The ghost is eliminated by turning it into a fakeon, that is to say a purely virtual particle. We work to the next-to-leading order of the expansion around the de Sitter background. The consistency of the approach puts a lower bound ($m_{\chi }>m_{\phi }/4$) on the mass $m_{\chi }$ of the fakeon with respect to the mass $m_{\phi }$ of the inflaton. The tensor-to-scalar ratio $r$ is predicted within less than an order of magnitude ($4/3<N^{2}r<12$ to the leading order in the number of $e$-foldings $N$). Moreover, the relation $r\simeq -8n_{T}$ is not affected by the Weyl-squared term. No vector and no other scalar/tensor degree of freedom is present.

We study the quantum Hall effect inside a gravitational field. First, we review the influence of the gravitational field of the Earth on the quantum Hall effect. Taking the gravitational field of the Earth to be uniform along the vertical direction, we compute the affected quantized Hall resistivity. Then, we investigate how the gravitational field modifies the Landau levels of a particle moving between two massive hemispheres in the presence of a constant and uniform magnetic field perpendicular to the plane of motion. We find that the familiar degeneracy of the Landau levels is removed and the spacing between the latter becomes dependent on the mass density of the hemispheres and on the gravitational constant $G$. We use this result to show that the quantum Hall effect in a thin conductor, sandwiched between two massive hemispheres, should yield a slightly different variation of the Hall resistivity with the applied magnetic field. We then argue that the well-known problem of the gravitationally induced electric field, that might a priori be thought to hinder the effect of gravity, has actually a beneficial role as it amplifies the latter. We finally discuss whether there is a possibility of using the quantum Hall effect to probe the inverse-square law of gravity.

We study the equivalence principle, regarded as the cornerstone of general relativity, by analyzing the deformation observable of black hole shadows. Such deformation can arise from new physics and may be expressed as a phenomenological violation of the equivalence principle. Specifically, we assume that there is an additional background vector field that couples to the photons around the supermassive black hole. This type of coupling yields impact on the way the system depends on initial conditions, and affects the black hole shadow at different wavelengths by a different amount, and therefore observations of the shadow in different wavelengths could constrain such couplings. This can be tested by future multi-band observations. Adopting a specific form of the vector field, we obtain constraints on model parameters from Event Horizon Telescope observations and measurements of gas/stellar orbits.

We show that the formation/evaporation of Black Holes (BH) unitarizes quantum gravity at all the orders of the perturbation theory. Non-perturbative quantum effects save the scattering amplitudes from any polynomial divergences. Such a phenomena is intimately related to the dynamical emergence of an effective non-locality as well as emergent modifications of the Heisenberg’s uncertainty principle. The BH production de-localizes quantum gravity vertices and propagators as a consequence of its holographically stored entropy. In this sense, quantum gravity is a superrenormalizable theory, although non-locality is hidden in its action.

 2020年5月22日 星期五 上午10:47 | Philsci-Archive: No conditions. Results ordered -Date Deposited.
Wuthrich, Christian and Huggett, Nick (2020) Out of Nowhere: Spacetime from causality: causal set theory. [Preprint]
 2020年5月22日 星期五 上午10:43 | Philsci-Archive: No conditions. Results ordered -Date Deposited.
Huggett, Nick and Wuthrich, Christian (2020) Out of Nowhere: The ’emergence’ of spacetime in string theory. [Preprint]
 2020年5月21日 星期四 下午6:00 | Lorenzo Maccone and Changliang Ren | PRL: General Physics: Statistical and Quantum Mechanics, Quantum Information, etc.

Author(s): Lorenzo Maccone and Changliang Ren

An object’s distance and direction could be measured in a new radar scheme that uses entangled photons, something unachievable with previous quantum radar proposals.

[Phys. Rev. Lett. 124, 200503] Published Thu May 21, 2020

 2020年5月21日 星期四 上午11:45 | Philsci-Archive: No conditions. Results ordered -Date Deposited.
savelyev, Yasha (2020) Universal G\”odel statements and computability of intelligence. [Preprint]
 2020年5月21日 星期四 上午11:39 | Philsci-Archive: No conditions. Results ordered -Date Deposited.
Huggett, Nick and Wuthrich, Christian (2020) Out of Nowhere: The ’emergence’ of spacetime. [Preprint]
 2020年5月19日 星期二 上午8:00 | Latest Results for Foundations of Physics

Abstract

QBism is one of the main candidates for an epistemic interpretation of quantum mechanics. According to QBism, the quantum state or the wavefunction represents the subjective degrees of belief of the agent assigning the state. But, although the quantum state is not part of the furniture of the world, quantum mechanics grasps the real via the Born rule which is a consistency condition for the probability assignments of the agent. In this paper, we evaluate the plausibility of recent criticism of QBism. We focus on the consequences of the subjective character of the quantum state, the issue of realism and the problem of the evolution of the quantum state in QBism. In particular, drawing upon Born’s notion of invariance as the mark of the real, it is argued that there is no essential difference between Einstein’s program of ‘the real’ and QBists’ realism. Also, it will be argued that QBism can account for the unitary evolution of the quantum state.

 2020年5月18日 星期一 下午3:16 | Philsci-Archive: No conditions. Results ordered -Date Deposited.
Linford, Daniel (2020) Big Bounce or Double Bang? A Reply to Craig & Sinclair on the Interpretation of Bounce Cosmologies. [Preprint]
 2020年5月18日 星期一 上午8:00 | Latest Results for Foundations of Physics

Abstract

The Hilbert space formalism describes causality as a statistical relation between initial experimental conditions and final measurement outcomes, expressed by the inner products of state vectors representing these conditions. This representation of causality is in fundamental conflict with the classical notion that causality should be expressed in terms of the continuity of intermediate realities. Quantum mechanics essentially replaces this continuity of reality with phase sensitive superpositions, all of which need to interfere in order to produce the correct conditional probabilities for the observable input-output relations. In this paper, I investigate the relation between the classical notion of reality and quantum superpositions by identifying the conditions under which the intermediate states can have real external effects, as expressed by measurement operators inserted into the inner product. It is shown that classical reality emerges at the macroscopic level, where the relevant limit of the measurement resolution is given by the variance of the action around the classical solution. It is thus possible to demonstrate that the classical notion of objective reality emerges only at the macroscopic level, where observations are limited to low resolutions by a lack of sufficiently strong intermediate interactions. This result indicates that causality is more fundamental to physics than the notion of an objective reality, which means that the apparent contradictions between quantum physics and classical physics may be resolved by carefully distinguishing between observable causality and unobservable sequences of hypothetical realities “out there”.

 2020年5月18日 星期一 上午8:00 | Latest Results for Synthese

Abstract

Distance, it is often argued, is the only coherent and empirically adequate world-making relation that can glue together the elements of the world. This paper offers entanglement as an alternative world-making relation. Entanglement is interesting since it is consistent even with quantum gravity theories that do not feature space at the fundamental level. The paper thereby defends the metaphysical salience of such non-spatial theories. An account of distance (space) is the predominant problem of empirical adequacy facing entanglement as a world-making relation. A resolution of this obstacle utilizes insights from the Ryu–Takayanagi formula (a holographic relation between entanglement and spacetime) and Susskind and Maldacena’s related ER = EPR conjecture (a relation between bell pairs and wormholes). Together these indicate how distance can be recovered from entanglement and thus carves the way for entanglement fundamentalism.

 2020年5月17日 星期日 上午5:52 | Philsci-Archive: No conditions. Results ordered -Date Deposited.
Martens, Niels C.M. and Read, James (2020) Sophistry about symmetries? Synthese. ISSN 1573-0964


text:
Twin law

The twin law is the set of twin operations mapping two individuals of a twin. It is obtained by coset decomposition of the point group of the twin lattice with respect to the intersection group of the point groups of the individuals in their respective orientations. Each operation in the same coset is a possible twin operation that, from the lattice viewpoint, is equivalent to any other operation in the same coset. Any of these can be taken as coset representative and indicated by the symbol of the twin element: $\bar 1$, [uvw] and (hkl) for the centre (inversion twin), direction of the rotation axis (rotation twin) and Miller indices of the mirror plane (reflection twin), in that order. Except when one refers to a specific plane or direction, the symbols {hkl} or <uvw> have to be be used to indicate all the planes or directions which belong to the same coset and are therefore equivalent under the point group of the individual.


text:
# Tutorial 1: GLMs for Encoding¶

Week 1, Day 4: Generalized Linear Models

Content creators: Pierre-Etienne H. Fiquet, Ari Benjamin, Jakob Macke

Content reviewers: Davide Valeriani, Alish Dipani, Michael Waskom, Ella Batty

# Tutorial Objectives¶

Estimated timing of tutorial: 1 hour, 15 minutes

This is part 1 of a 2-part series about Generalized Linear Models (GLMs), which are a fundamental framework for supervised learning.

In this tutorial, the objective is to model a retinal ganglion cell spike train by fitting a temporal receptive field. First with a Linear-Gaussian GLM (also known as ordinary least-squares regression model) and then with a Poisson GLM (aka “Linear-Nonlinear-Poisson” model). In the next tutorial, we’ll extend to a special case of GLMs, logistic regression, and learn how to ensure good model performance.

This tutorial is designed to run with retinal ganglion cell spike train data from Uzzell & Chichilnisky 2004.

Acknowledgements:

• We thank EJ Chichilnisky for providing the dataset. Please note that it is provided for tutorial purposes only, and should not be distributed or used for publication without express permission from the author (ej@stanford.edu).

• We thank Jonathan Pillow, much of this tutorial is inspired by exercises asigned in his ‘Statistical Modeling and Analysis of Neural Data’ class.

## Tutorial slides¶

These are the slides for the videos in all tutorials today

# Setup¶

# Imports

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

## Figure settings¶

#@title Figure settings
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

## Plotting Functions¶

# @title Plotting Functions

def plot_stim_and_spikes(stim, spikes, dt, nt=120):
"""Show time series of stim intensity and spike counts.

Args:
stim (1D array): vector of stimulus intensities
spikes (1D array): vector of spike counts
dt (number): duration of each time step
nt (number): number of time steps to plot

"""
timepoints = np.arange(120)
time = timepoints * dt

f, (ax_stim, ax_spikes) = plt.subplots(
nrows=2, sharex=True, figsize=(8, 5),
)
ax_stim.plot(time, stim[timepoints])
ax_stim.set_ylabel('Stimulus intensity')

ax_spikes.plot(time, spikes[timepoints])
ax_spikes.set_xlabel('Time (s)')
ax_spikes.set_ylabel('Number of spikes')

f.tight_layout()

def plot_glm_matrices(X, y, nt=50):
"""Show X and Y as heatmaps.

Args:
X (2D array): Design matrix.
y (1D or 2D array): Target vector.

"""
from matplotlib.colors import BoundaryNorm
from mpl_toolkits.axes_grid1 import make_axes_locatable
Y = np.c_[y]  # Ensure Y is 2D and skinny

f, (ax_x, ax_y) = plt.subplots(
ncols=2,
figsize=(6, 8),
sharey=True,
gridspec_kw=dict(width_ratios=(5, 1)),
)
norm = BoundaryNorm([-1, -.2, .2, 1], 256)
imx = ax_x.pcolormesh(X[:nt], cmap="coolwarm", norm=norm)

ax_x.set(
title="X\n(lagged stimulus)",
xlabel="Time lag (time bins)",
xticks=[4, 14, 24],
xticklabels=['-20', '-10', '0'],
ylabel="Time point (time bins)",
)
plt.setp(ax_x.spines.values(), visible=True)

divx = make_axes_locatable(ax_x)
cbarx = f.colorbar(imx, cax=caxx)
cbarx.set_ticks([-.6, 0, .6])
cbarx.set_ticklabels(np.sort(np.unique(X)))

norm = BoundaryNorm(np.arange(y.max() + 1), 256)
imy = ax_y.pcolormesh(Y[:nt], cmap="magma", norm=norm)
ax_y.set(
title="Y\n(spike count)",
xticks=[]
)
ax_y.invert_yaxis()
plt.setp(ax_y.spines.values(), visible=True)

divy = make_axes_locatable(ax_y)
cbary = f.colorbar(imy, cax=caxy)
cbary.set_ticks(np.arange(y.max()) + .5)
cbary.set_ticklabels(np.arange(y.max()))

def plot_spike_filter(theta, dt, **kws):
"""Plot estimated weights based on time lag model.

Args:
theta (1D array): Filter weights, not including DC term.
dt (number): Duration of each time bin.
kws: Pass additional keyword arguments to plot()

"""
d = len(theta)
t = np.arange(-d + 1, 1) * dt

ax = plt.gca()
ax.plot(t, theta, marker="o", **kws)
ax.axhline(0, color=".2", linestyle="--", zorder=1)
ax.set(
xlabel="Time before spike (s)",
ylabel="Filter weight",
)

def plot_spikes_with_prediction(
spikes, predicted_spikes, dt, nt=50, t0=120, **kws):
"""Plot actual and predicted spike counts.

Args:
spikes (1D array): Vector of actual spike counts
predicted_spikes (1D array): Vector of predicted spike counts
dt (number): Duration of each time bin.
nt (number): Number of time bins to plot
t0 (number): Index of first time bin to plot.
kws: Pass additional keyword arguments to plot()

"""
t = np.arange(t0, t0 + nt) * dt

f, ax = plt.subplots()
lines = ax.stem(t, spikes[:nt], use_line_collection=True)
plt.setp(lines, color=".5")
lines[-1].set_zorder(1)
kws.setdefault("linewidth", 3)
yhat, = ax.plot(t, predicted_spikes[:nt], **kws)
ax.set(
xlabel="Time (s)",
ylabel="Spikes",
)
ax.yaxis.set_major_locator(plt.MaxNLocator(integer=True))
ax.legend([lines[0], yhat], ["Spikes", "Predicted"])

plt.show()

#@title Data retrieval and loading
import os
import hashlib
import requests

fname = "RGCdata.mat"
expected_md5 = "1b2977453020bce5319f2608c94d38d0"

if not os.path.isfile(fname):
try:
r = requests.get(url)
except requests.ConnectionError:
else:
if r.status_code != requests.codes.ok:
elif hashlib.md5(r.content).hexdigest() != expected_md5:
else:
with open(fname, "wb") as fid:
fid.write(r.content)

# Section 1: Linear-Gaussian GLM¶

## Section 1.1: Load retinal ganglion cell activity data¶

Estimated timing to here from start of tutorial: 10 min

In this exercise we use data from an experiment that presented a screen which randomly alternated between two luminance values and recorded responses from retinal ganglion cell (RGC), a type of neuron in the retina in the back of the eye. This kind of visual stimulus is called a “full-field flicker”, and it was presented at ~120Hz (ie. the stimulus presented on the screen was refreshed about every 8ms). These same time bins were used to count the number of spikes emitted by each neuron.

The file RGCdata.mat contains three variablies:

• Stim, the stimulus intensity at each time point. It is an array with shape $$T \times 1$$, where $$T=144051$$.

• SpCounts, the binned spike counts for 2 ON cells, and 2 OFF cells. It is a $$144051 \times 4$$ array, and each column has counts for a different cell.

• dtStim, the size of a single time bin (in seconds), which is needed for computing model output in units of spikes / s. The stimulus frame rate is given by 1 / dtStim.

Because these data were saved in MATLAB, where everything is a matrix, we will also process the variables to more Pythonic representations (1D arrays or scalars, where appropriate) as we load the data.

data = loadmat('RGCdata.mat')  # loadmat is a function in scipy.io
dt_stim = data['dtStim'].item()  # .item extracts a scalar value

# Extract the stimulus intensity
stim = data['Stim'].squeeze()  # .squeeze removes dimensions with 1 element

# Extract the spike counts for one cell
cellnum = 2
spikes = data['SpCounts'][:, cellnum]

# Don't use all of the timepoints in the dataset, for speed
keep_timepoints = 20000
stim = stim[:keep_timepoints]
spikes = spikes[:keep_timepoints]

Use the plot_stim_and_spikes helper function to visualize the changes in stimulus intensities and spike counts over time.

plot_stim_and_spikes(stim, spikes, dt_stim)

### Coding Exercise 1.1: Create design matrix¶

Our goal is to predict the cell’s activity from the stimulus intensities preceding it. That will help us understand how RGCs process information over time. To do so, we first need to create the design matrix for this model, which organizes the stimulus intensities in matrix form such that the $$i$$th row has the stimulus frames preceding timepoint $$i$$.

In this exercise, we will create the design matrix $$\mathbf{X}$$ using $$d=25$$ time lags. That is, $$\mathbf{X}$$ should be a $$T \times d$$ matrix. $$d = 25$$ (about 200 ms) is a choice we’re making based on our prior knowledge of the temporal window that influences RGC responses. In practice, you might not know the right duration to use.

The last entry in row t should correspond to the stimulus that was shown at time t, the entry to the left of it should contain the value that was show one time bin earlier, etc. Specifically, $$X_{ij}$$ will be the stimulus intensity at time $$i + d - 1 - j$$.

Note that for the first few time bins, we have access to the recorded spike counts but not to the stimulus shown in the recent past. For simplicity we are going to assume that values of stim are 0 for the time lags prior to the first timepoint in the dataset. This is known as “zero-padding”, so that the design matrix has the same number of rows as the response vectors in spikes.

• make a zero-padded version of the stimulus

• initialize an empty design matrix with the correct shape

• fill in each row of the design matrix, using the zero-padded version of the stimulus

To visualize your design matrix (and the corresponding vector of spike counts), we will plot a “heatmap”, which encodes the numerical value in each position of the matrix as a color. The helper functions include some code to do this.

def make_design_matrix(stim, d=25):
"""Create time-lag design matrix from stimulus intensity vector.

Args:
stim (1D array): Stimulus intensity at each time point.
d (number): Number of time lags to use.

Returns
X (2D array): GLM design matrix with shape T, d

"""

# Create version of stimulus vector with zeros before onset
padded_stim = np.concatenate([np.zeros(d - 1), stim])

#####################################################################
# Fill in missing code (...),
# then remove or comment the line below to test your function
raise NotImplementedError("Complete the make_design_matrix function")
#####################################################################

# Construct a matrix where each row has the d frames of
# the stimulus proceeding and including timepoint t
T = len(...)  # Total number of timepoints (hint: number of stimulus frames)
X = np.zeros((T, d))
for t in range(T):
X[t] = ...

return X

# Make design matrix
X = make_design_matrix(stim)

# Visualize
plot_glm_matrices(X, spikes, nt=50)

Click for solution

Example output:

## Section 1.2: Fit Linear-Gaussian regression model¶

Estimated timing to here from start of tutorial: 25 min

First, we will use the design matrix to compute the maximum likelihood estimate for a linear-Gaussian GLM (aka “general linear model”). The maximum likelihood estimate of $$\theta$$ in this model can be solved analytically using the equation you learned about on Day 3:

(89)\begin{align} \boldsymbol{\hat \theta} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y} \end{align}

Before we can apply this equation, we need to augment the design matrix to account for the mean of $$y$$, because the spike counts are all $$\geq 0$$. We do this by adding a constant column of 1’s to the design matrix, which will allow the model to learn an additive offset weight. We will refer to this additional weight as $$b$$ (for bias), although it is alternatively known as a “DC term” or “intercept”.

# Build the full design matrix
y = spikes
constant = np.ones_like(y)
X = np.column_stack([constant, make_design_matrix(stim)])

# Get the MLE weights for the LG model
theta = np.linalg.inv(X.T @ X) @ X.T @ y
theta_lg = theta[1:]

Plot the resulting maximum likelihood filter estimate (just the 25-element weight vector $$\theta$$ on the stimulus elements, not the DC term $$b$$).

plot_spike_filter(theta_lg, dt_stim)

### Coding Exercise 1.2: Predict spike counts with Linear-Gaussian model¶

Now we are going to put these pieces together and write a function that outputs a predicted spike count for each timepoint using the stimulus information.

• Create the complete design matrix

• Obtain the MLE weights ($$\boldsymbol{\hat \theta}$$)

• Compute $$\mathbf{\hat y} = \mathbf{X}\boldsymbol{\hat \theta}$$

def predict_spike_counts_lg(stim, spikes, d=25):
"""Compute a vector of predicted spike counts given the stimulus.

Args:
stim (1D array): Stimulus values at each timepoint
spikes (1D array): Spike counts measured at each timepoint
d (number): Number of time lags to use.

Returns:
yhat (1D array): Predicted spikes at each timepoint.

"""
##########################################################################
# Fill in missing code (...) and then comment or remove the error to test
raise NotImplementedError("Complete the predict_spike_counts_lg function")
##########################################################################

# Create the design matrix
y = spikes
constant = ...
X = ...

# Get the MLE weights for the LG model
theta = ...

# Compute predicted spike counts
yhat = X @ theta

return yhat

# Predict spike counts
predicted_counts = predict_spike_counts_lg(stim, spikes)

# Visualize
plot_spikes_with_prediction(spikes, predicted_counts, dt_stim)

Click for solution

Example output:

Is this a good model? The prediction line more-or-less follows the bumps in the spikes, but it never predicts as many spikes as are actually observed. And, more troublingly, it’s predicting negative spikes for some time points.

The Poisson GLM will help to address these failures.

### Bonus challenge¶

The “spike-triggered average” falls out as a subcase of the linear Gaussian GLM: $$\mathrm{STA} = \mathbf{X}^T \mathbf{y} \,/\, \textrm{sum}(\mathbf{y})$$, where $$\mathbf{y}$$ is the vector of spike counts of the neuron. In the LG GLM, the term $$(\mathbf{X}^T\mathbf{X})^{-1}$$ corrects for potential correlation between the regressors. Because the experiment that produced these data used a white noise stimulus, there are no such correlations. Therefore the two methods are equivalent. (How would you check the statement about no correlations?)

# Section 2: Linear-Nonlinear-Poisson GLM¶

Estimated timing to here from start of tutorial: 36 min

## Section 2.1: Nonlinear optimization with scipy.optimize¶

Estimated timing to here from start of tutorial: 45 min

Before diving into the Poisson GLM case, let us review the use and importance of convexity in optimization:

• We have seen previously that in the Linear-Gaussian case, maximum likelihood parameter estimate can be computed analytically. That is great because it only takes us a single line of code!

• Unfortunately in general there is no analytical solution to our statistical estimation problems of interest. Instead, we need to apply a nonlinear optimization algorithm to find the parameter values that minimize some objective function. This can be extremely tedious because there is no general way to check whether we have found the optimal solution or if we are just stuck in some local minimum.

• Somewhere in between these two extremes, the special case of convex objective function is of great practical importance. Indeed, such optimization problems can be solved very reliably (and usually quite rapidly too!) using some standard software.

Notes:

• a function is convex if and only if its curve lies below any chord joining two of its points

• to learn more about optimization, you can consult the book of Stephen Boyd and Lieven Vandenberghe Convex Optimization.

Here we will use the scipy.optimize module, it contains a function called minimize that provides a generic interface to a large number of optimization algorithms. This function expects as argument an objective function and an “initial guess” for the parameter values. It then returns a dictionary that includes the minimum function value, the parameters that give this minimum, and other information.

Let’s see how this works with a simple example. We want to minimize the function $$f(x) = x^2$$:

f = np.square

res = minimize(f, x0=2)
print(
f"Minimum value: {res['fun']:.4g}",
f"at x = {res['x']}",
)

Minimum value: 3.566e-16 at x = [-1.88846401e-08]

When minimizing a $$f(x) = x^2$$, we get a minimum value of $$f(x) \approx 0$$ when $$x \approx 0$$. The algorithm doesn’t return exactly $$0$$, because it stops when it gets “close enough” to a minimum. You can change the tol parameter to control how it defines “close enough”.

A point about the code bears emphasis. The first argument to minimize is not a number or a string but a function. Here, we used np.square. Take a moment to make sure you understand what’s going on, because it’s a bit unusual, and it will be important for the exercise you’re going to do in a moment.

In this example, we started at $$x_0 = 2$$. Let’s try different values for the starting point:

start_points = -1, 1.5

xx = np.linspace(-2, 2, 100)
plt.plot(xx, f(xx), color=".2")
plt.xlabel("$x$")
plt.ylabel("$f(x)$")

for i, x0 in enumerate(start_points):
res = minimize(f, x0)
plt.plot(x0, f(x0), "o", color=f"C{i}", ms=10, label=f"Start {i}")
plt.plot(res["x"].item(), res["fun"], "x", c=f"C{i}", ms=10, mew=2, label=f"End {i}")
plt.legend()

The runs started at different points (the dots), but they each ended up at roughly the same place (the cross): $$f(x_\textrm{final}) \approx 0$$. Let’s see what happens if we use a different function:

g = lambda x: x / 5 + np.cos(x)
start_points = -.5, 1.5

xx = np.linspace(-4, 4, 100)
plt.plot(xx, g(xx), color=".2")
plt.xlabel("$x$")
plt.ylabel("$f(x)$")

for i, x0 in enumerate(start_points):
res = minimize(g, x0)
plt.plot(x0, g(x0), "o", color=f"C{i}", ms=10, label=f"Start {i}")
plt.plot(res["x"].item(), res["fun"], "x", color=f"C{i}", ms=10, mew=2, label=f"End {i}")
plt.legend()

Unlike $$f(x) = x^2$$, $$g(x) = \frac{x}{5} + \cos(x)$$ is not convex. We see that the final position of the minimization algorithm depends on the starting point, which adds a layer of comlpexity to such problems.

### Coding Exercise 2.1: Fitting the Poisson GLM and prediction spikes¶

In this exercise, we will use scipy.optimize.minimize to compute maximum likelihood estimates for the filter weights in the Poissson GLM model with an exponential nonlinearity (LNP: Linear-Nonlinear-Poisson).

In practice, this will involve filling out two functions.

• The first should be an objective function that takes a design matrix, a spike count vector, and a vector of parameters. It should return a negative log likelihood.

• The second function should take stim and spikes, build the design matrix and then use minimize internally, and return the MLE parameters.

What should the objective function look like? We want it to return the negative log likelihood: $$-\log P(y \mid \mathbf{X}, \theta).$$

In the Poisson GLM,

(90)\begin{align} \log P(\mathbf{y} \mid \mathbf{X}, \theta) = \sum_t \log P(y_t \mid \mathbf{x_t},\theta), \end{align}

where

(91)\begin{align} P(y_t \mid \mathbf{x_t}, \theta) = \frac{\lambda_t^{y_t}\exp(-\lambda_t)}{y_t!} \text{, with rate } \lambda_t = \exp(\mathbf{x_t}^{\top} \theta). \end{align}

Now, taking the log likelihood for all the data we obtain: $$\log P(\mathbf{y} \mid X, \theta) = \sum_t( y_t \log\left(\lambda_t) - \lambda_t - \log(y_t !)\right).$$

Because we are going to minimize the negative log likelihood with respct to the parameters $$\theta$$, we can ignore the last term that does not depend on $$\theta$$. For faster implementation, let us rewrite this in matrix notation:

(92)\begin{align} \mathbf{y}^T \log(\mathbf{\lambda}) - \mathbf{1}^T \mathbf{\lambda} \text{, with rate } \mathbf{\lambda} = \exp(\mathbf{X}^{\top} \theta) \end{align}

Finally, don’t forget to add the minus sign for your function to return the negative log likelihood.

def neg_log_lik_lnp(theta, X, y):
"""Return -loglike for the Poisson GLM model.

Args:
theta (1D array): Parameter vector.
X (2D array): Full design matrix.
y (1D array): Data values.

Returns:
number: Negative log likelihood.

"""
#####################################################################
# Fill in missing code (...), then remove the error
raise NotImplementedError("Complete the neg_log_lik_lnp function")
#####################################################################

# Compute the Poisson log likeliood
rate = np.exp(X @ theta)
log_lik = y @ ... - ...

return ...

def fit_lnp(stim, spikes, d=25):
"""Obtain MLE parameters for the Poisson GLM.

Args:
stim (1D array): Stimulus values at each timepoint
spikes (1D array): Spike counts measured at each timepoint
d (number): Number of time lags to use.

Returns:
1D array: MLE parameters

"""
#####################################################################
# Fill in missing code (...), then remove the error
raise NotImplementedError("Complete the fit_lnp function")
#####################################################################

# Build the design matrix
y = spikes
constant = np.ones_like(y)
X = np.column_stack([constant, make_design_matrix(stim)])

# Use a random vector of weights to start (mean 0, sd .2)
x0 = np.random.normal(0, .2, d + 1)

# Find parameters that minmize the negative log likelihood function
res = minimize(..., args=(X, y))

return ...

# Fit LNP model
theta_lnp = fit_lnp(stim, spikes)

# Visualize
plot_spike_filter(theta_lg[1:], dt_stim, color=".5", label="LG")
plot_spike_filter(theta_lnp[1:], dt_stim, label="LNP")
plt.legend(loc="upper left");

Click for solution

Example output:

Plotting the LG and LNP weights together, we see that they are broadly similar, but the LNP weights are generally larger. What does that mean for the model’s ability to predict spikes? To see that, let’s finish the exercise by filling out the predict_spike_counts_lnp function:

def predict_spike_counts_lnp(stim, spikes, theta=None, d=25):
"""Compute a vector of predicted spike counts given the stimulus.

Args:
stim (1D array): Stimulus values at each timepoint
spikes (1D array): Spike counts measured at each timepoint
theta (1D array): Filter weights; estimated if not provided.
d (number): Number of time lags to use.

Returns:
yhat (1D array): Predicted spikes at each timepoint.

"""
###########################################################################
# Fill in missing code (...) and then remove the error to test
raise NotImplementedError("Complete the predict_spike_counts_lnp function")
###########################################################################

y = spikes
constant = np.ones_like(spikes)
X = np.column_stack([constant, make_design_matrix(stim)])
if theta is None:  # Allow pre-cached weights, as fitting is slow
theta = fit_lnp(X, y, d)

yhat = ...
return yhat

# Predict spike counts
yhat = predict_spike_counts_lnp(stim, spikes, theta_lnp)

# Visualize
plot_spikes_with_prediction(spikes, yhat, dt_stim)

Click for solution

Example output:

We see that the LNP model does a better job of fitting the actual spiking data. Importantly, it never predicts negative spikes!

Bonus: Our statement that the LNP model “does a better job” is qualitative and based mostly on the visual appearance of the plot. But how would you make this a quantitative statement?

# Summary¶

Estimated timing of tutorial: 1 hour, 15 minutes

In this first tutorial, we used two different models to learn something about how retinal ganglion cells respond to a flickering white noise stimulus. We learned how to construct a design matrix that we could pass to different GLMs, and we found that the Linear-Nonlinear-Poisson (LNP) model allowed us to predict spike rates better than a simple Linear-Gaussian (LG) model.

In the next tutorial, we’ll extend these ideas further. We’ll meet yet another GLM — logistic regression — and we’ll learn how to ensure good model performance even when the number of parameters d is large compared to the number of data points N.

# Notation¶

(93)\begin{align} y &\quad \text{measurement or response, here: spike count}\\ T &\quad \text{number of time points}\\ d &\quad \text{input dimensionality}\\ \mathbf{X} &\quad \text{design matrix, dimensions: } T \times d\\ \theta &\quad \text{parameter}\\ \hat \theta &\quad \text{estimated parameter}\\ \hat y &\quad \text{estimated response}\\ P(\mathbf{y} \mid \mathbf{X}, \theta) &\quad \text{probability of observing response } y \text{ given design matrix } \mathbf{X} \text{ and parameters } \theta \\ \mathrm{STA} &\quad \text{spike-triggered average}\\ b &\quad \text{bias weight, intercept}\\ \end{align}


text:
# Prove P(x) >= M

$P(x) = a_nx^n +a_{n-1}x^{n-1} + \ldots + a_1x + a_0,$ n>=1
Clearly, as $x\to\infty,\ a_nx^n\to\infty$. Show that, as x --> infinity, $P(x)\to\infty$ by showing that, given any positive number M, there exists a positive number K such that if x>=K, then P(x) >=M.
(Hint: you might wish to choose $K_i>0$ such that
$|a_{n-i}/x^i|< a_n/2n$ when $x > K_i$ and then take the largest of the $K_i$. )


text:
# Journal of theKorean Mathematical SocietyJKMS

ISSN(Print) 0304-9914 ISSN(Online) 2234-3008

## Article

HOME ALL ARTICLES View

J. Korean Math. Soc. 2022; 59(1): 13-33

Published online January 1, 2022 https://doi.org/10.4134/JKMS.j200626

## Parabolic quaternionic Monge-Amp\{e}re equation on compact manifolds with a flat hyperK\"ahler metric

Jiaogen Zhang

University of Science and Technology of China

### Abstract

The quaternionic Calabi conjecture was introduced by Alesker-Verbitsky, analogous to the K\"ahler case which was raised by Calabi. On a compact connected hypercomplex manifold, when there exists a  flat hyperK\"ahler metric which is compatible with the underlying hypercomplex structure, we will consider the parabolic quaternionic Monge-Amp\{e}re equation.  Our goal is to prove the long time existence and $C^{\infty}$ convergence for normalized solutions  as $t\rightarrow\infty$. As a consequence, we show that the limit function is exactly the solution of quaternionic Monge-Amp\`{e}re equation, this gives a parabolic proof for the quaternionic Calabi conjecture in this special setting.

Keywords: A priori estimates, hyperK\"ahler manifold with torsion, parabolic quaternionic \MA~equation

MSC numbers: 35B45, 53C26, 35J96


text:
# 「POJ-1006」Biorhythms-中国剩余定理

Some people believe that there are three cycles in a person’s life that start the day he or she is born. These three cycles are the physical, emotional, and intellectual cycles, and they have periods of lengths 23, 28, and 33 days, respectively. There is one peak in each period of a cycle. At the peak of a cycle, a person performs at his or her best in the corresponding field (physical, emotional or mental). For example, if it is the mental curve, thought processes will be sharper and concentration will be easier.

# 「POJ-2115」C Looooops-扩展欧几里德

A Compiler Mystery: We are given a C-language style for loop of type
for (variable = A; variable != B; variable += C)

statement;

I.e., a loop which starts by setting variable to value A and while variable is not equal to B, repeats statement followed by increasing the variable by C. We want to know how many times does the statement get executed for particular values of A, B and C, assuming that all arithmetics is calculated in a k-bit unsigned integer type (with values 0 <= x < 2 k) modulo 2 k.

# 「CF-527A」Playing with Paper-模拟

One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm  ×  b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.

# 「POJ-3090」Visible Lattice Points-欧拉函数

A lattice point (x, y) in the first quadrant (x and y are integers greater than or equal to 0), other than the origin, is visible from the origin if the line from (0, 0) to (x, y) does not pass through any other lattice point. For example, the point (4, 2) is not visible since the line from the origin passes through (2, 1). The figure below shows the points (x, y) with 0 \leq x, y \leq 5 with lines from the origin to the visible points.

# 「POJ-3421」X-factor Chains-质因数分解

Given a positive integer X, an X-factor chain of length m is a sequence of integers,

$1 = X_0, X_1, X_2, \cdots , X_m = X$

satisfying

$X_i < X_i+1$ and $X_i | X_i+1$ where a | b means a perfectly divides into b.

Now we are interested in the maximum length of X-factor chains and the number of chains of such length.

# 「POJ-2689」Prime Distance-线筛

The branch of mathematics called number theory is about properties of numbers. One of the areas that has captured the interest of number theoreticians for thousands of years is the question of primality. A prime number is a number that is has no proper factors (it is only evenly divisible by 1 and itself). The first prime numbers are 2,3,5,7 but they quickly become less frequent. One of the interesting questions is how dense they are in various ranges. Adjacent primes are two numbers that are both primes, but there are no other prime numbers between the adjacent primes. For example, 2,3 are the only adjacent primes that are also adjacent numbers.
Your program is given 2 numbers: L and U (1<=L< U<=2,147,483,647), and you are to find the two adjacent primes C1 and C2 (L<=C1< C2<=U) that are closest (i.e. C2-C1 is the minimum). If there are other pairs that are the same distance apart, use the first pair. You are also to find the two adjacent primes D1 and D2 (L<=D1< D2<=U) where D1 and D2 are as distant from each other as possible (again choosing the first pair if there is a tie).

bzoj2194

bzoj2179

# 「NOIP2016」组合数问题 - 递推 + 前缀和

$C_n ^ m = \frac{n!}{m!(n - m)!}$


text:
A series LCR circuit is designed to resonate at an angular frequency
Question:

A series LCR circuit is designed to resonate at an angular frequency $\omega_{0}=10^{5} \mathrm{rad} / \mathrm{s}$.

The circuit draws $16 \mathrm{~W}$ power from $120 \mathrm{~V}$ source at resonance. The value of

resistance ‘ $\mathrm{R}^{\prime}$ in the circuit is $\Omega$

Solution:

(900)

$P=\frac{V^{2}}{R}$

$16=\frac{120^{2}}{R} \Rightarrow R=\frac{14400}{16}$

$\Rightarrow R=900 \Omega$


text:
Beginner DX12 Instancing

Instancing with Direct3D12

Microsoft was kind enough to provide a working Direct3D12 Sample for Universal Windows Platform (UWP) as a template with VS2017. Unfortunately, if you've even attempted to ever play with previous versions of DirectX, you may find that Direct3D12 is really picky and it's easy to mess yourself up and wind up scratching your head. If you want to redraw the cube from the demo in more than one place, you can't simply go into the Render function to make your transformations and draw calls within a basic for loop like I did in: https://www.utilars.com/Blog/shawn-eary/2012/12/16/cubeCloneWin8

In DirectX12 you are forced to manage the GPU(s) more directly so you can have the ultimate in performance. This means the API will not insulate you from silly mistakes. This means novices (like myself need to be vary wary of DirectX12. However, Despite DirectX12's added complexity, there is always going to be some newbie that likes banging her/his head against the wall... Becuase DirectX12 is more complicated, a different approach is needed to "easily" redraw the cube from the demo in more than one place. The easiest approach I found was instancing.

Unfortunately, D3D12 Instancing is apparently even harder than D3D11 Instancing. The good news though is that once you've done it, your code should be more efficient. At the time of this post, there didn't seem to be very many introductary examples on DirectX12 instancing so I will try to explain how I *think* I was able to get it to work in this blog post.

First off, open VS2017 Community Edition. Start a new project and pick the DirectX 12 App (Universal Windows) Visual C++ Template

After that, you will be shown a "New Universal Windows Platform Project" Window from which you are supposed to pick your target and minimum versions for your UWP app. I'm not really sure what the implications are of choosing the different options but for this example, we can simply choose "Windows 10, version 1803 (10.0; Build 17134) for Target version and Minimum version. This tutorial is simple enough that other versions will probably work as well, but it would be best to err on the side of more recent versions if you had to chose a different value.

After chosing your target and minimum versions, VS2017 will create a project for you. If you build it, you will see a simple rotating cube. When you get a chance, you need to stop the project and expand the Content folder to look at the Sample3DSceneRenderer.cpp file that Microsoft created for you.

Lot's of cool things happen in this file. This is were *most* of the changes will take place. In this particular picture you will see the cubVertices array. On the left side is each vertice of a triangle that will be rendered via your GPU. I *think* this data gets processed by something called a VertexShader on the GPU. On the right side, are colors for each of the vertices. I *think* that stuff is processed by something called a PixelShader on the GPU. You can play with this if you want but don't for get to make a copy of the original values or put this project into version control...

In the case of these particular vertices, a technique called indexing is used. I won't get into that here, but basically each vertex / color pair can be used zero or more times since it is referenced later by an index buffer. In simpiler DX examples, the vertices might be used directly, but in this Microsoft template, the vertices are indexed for possile reuse. This "potentially" allows for better performance and DX12 is *all* about bleeding edge performance. The only problem is novices (like myself) may not be able to fully achieve that expected performance due to a lack of understanding...

Regardless of operator understanding, the Verties and Indexes are sent to the GPU via Index and Vertex buffers and we are going to have to create a *new* buffer called an Instance Buffer. Because the GPU seems to be isolated from its surroundings, we are going to need a way to pass positional information to the GPU. As I said previously, we can't just translate the box and call the Draw call several times. We have to pass the positions of the cube copies to the GPU via a buffer. While there are *other* ways of getting this data to the GPU, this is the "easiest" way I found. According to the dude over at Rastertek, "Instancing is a method of rendering in DirectX 11 that eliminates this problem by accepting a single vertex buffer with the geometry and then uses a second buffer called an Instance Buffer which carries the modification information for each instance of the model geometry." - [1]
(If you haven't read the DX11 tutorial over at RasterTek, you might want to do so when you get a chance. It's doesn't explain DX12 or UWP, but it explains instancing better than I can...)

So now let's start creating the instance buffer. First, under content, double click your Sample3DSceneRenderer.h file. Insert the following inbetween the Microsoft supplied code:

...
// Direct3D resources for cube geometry.
Microsoft::WRL::ComPtr m_commandList;
Microsoft::WRL::ComPtr m_rootSignature;
Microsoft::WRL::ComPtr m_pipelineState;
Microsoft::WRL::ComPtr m_cbvHeap;
Microsoft::WRL::ComPtr m_vertexBuffer;

// Added by Instancing Tutorial: To Share Positional information with GPU
Microsoft::WRL::ComPtr m_instanceBuffer;

Microsoft::WRL::ComPtr m_indexBuffer;
Microsoft::WRL::ComPtr m_constantBuffer;
ModelViewProjectionConstantBuffer m_constantBufferData;
UINT8* m_mappedConstantBuffer;
UINT m_cbvDescriptorSize;
D3D12_RECT m_scissorRect;
std::vector m_vertexShader;
std::vector m_pixelShader;
D3D12_VERTEX_BUFFER_VIEW m_vertexBufferView;
D3D12_INDEX_BUFFER_VIEW m_indexBufferView;

// Added by Instancing Tutorial: Not sure what this does
D3D12_VERTEX_BUFFER_VIEW m_instanceBufferView;

...

This will declare your Instance Buffer and m_instanceBufferView. I'm going to be honest. I don't know what the m_instanceBufferView is for but I *think* I needed it...

Now, you need to tell the GPU that you will be sending some instancing data over. You need to open the Sample3DSceneRenderer.cpp file again and got to the CreateDeveiceDependentResources function. You need to look for the D3D12_INPUT_ELEMENT_DESC item. It happens to be called inputLayout and it's decribed really well in the Instance Buffer section of the Braynzar Soft Instancing tutorial at [2]

Currently, the Microsoft Code for that in CreateDeveiceDependentResources looks like this:

...
static const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
...

We will need to add a few lines like so:

...
static const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
{

// Microsoft Created Code: Data From Vertex Buffer

{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },

// Stuff We are Adding: Data From Instance Buffer
{ "INSTANCEPOS", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1},
{ "INSTANCECOLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 12, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1}

};
...

Pay particular attention to the fourth parameter for the structures in the inputLayout array. For the Vertex Buffer it is always 0 but for the Instance buffer it is always 1. Braynzar Soft explains in its D3D11 instancing tutorial that these are "slots" that in which the data will be loaded into the GPU for later retreival. The Vertex Buffer and Instance Buffer need to both be in different slots. Also, Braynzar Soft explains that the "POSITION", "COLOR", "INSTANCEPOS", and "INSTANCECOLOR" identifiers are "keys" that are later used by the Vertex Shader to retrieve the data. I'm thinking each of these keys need to be unique.

Now look down in the function for an array definition cubeVertices of type VertexPositionColor. The Microsoft code looks like this:

...
// Cube vertices. Each vertex has a position and a color.
VertexPositionColor cubeVertices[] =
{
{ XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f) },
{ XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f) },
{ XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f) },
{ XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f) },
{ XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f) },
{ XMFLOAT3(0.5f, -0.5f,  0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f) },
{ XMFLOAT3(0.5f,  0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f) },
{ XMFLOAT3(0.5f,  0.5f,  0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
};
...

We're not going to change this code, but we are going to add something similar in form just below it. For this tutorial, we are going to create six instances of the cube. So we will need six rows each containing position and color data. The color data will be ignored so we will set the RBG values to 1.0f for each color value in the second colum, but in the first column each XMFLOAT3 value will correspond to an instance based offset that will be used by the Vertex Shader to move the cube instance before displaying it. We are going to try to display a very basic cross or letter "t". I know this isn't the best artwork, but once you've sucessfully worked through this tutorial, you can put the cubes wherever you want:

...
// Cube vertices. Each vertex has a position and a color.
VertexPositionColor cubeVertices[] =
{
{ XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f) },
{ XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f) },
{ XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f) },
{ XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f) },
{ XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f) },
{ XMFLOAT3(0.5f, -0.5f,  0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f) },
{ XMFLOAT3(0.5f,  0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f) },
{ XMFLOAT3(0.5f,  0.5f,  0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
};

// Instance position data.  Second column data is color data
// and will be ignored for this tutorial since I don't want to
// mess with the Vertex Shader more than I need to.  The first
// column is what you want to pay attention to.  It should form
// the pattern of a simple cross or letter "t"
VertexPositionColor instanceVertices[] =
{
{ XMFLOAT3(-5.0f, 0.0f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
{ XMFLOAT3(0.0f, 0.0f,  0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
{ XMFLOAT3(5.0f, 0.0f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
{ XMFLOAT3(0.0f, -5.0f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
{ XMFLOAT3(0.0f, 5.0f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
{ XMFLOAT3(0.0f, 10.0f,  0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
};

...

Now, we need to upload this data to the GPU. We are going to take an easy approch for this. There is a chunk of code that Microsoft wrote that will upload the Vertex Buffer to the GPU. It looks like this:

...
const UINT vertexBufferSize = sizeof(cubeVertices);

// Create the vertex buffer resource in the GPU's default heap and copy vertex data into it using the upload heap.
// The upload resource must not be released until after the GPU has finished using it.
Microsoft::WRL::ComPtr
vertexBufferUpload;

CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
CD3DX12_RESOURCE_DESC vertexBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize);
DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
&defaultHeapProperties,
D3D12_HEAP_FLAG_NONE,
&vertexBufferDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(&m_vertexBuffer)));

...

// Upload the vertex buffer to the GPU.
{
D3D12_SUBRESOURCE_DATA vertexData = {};
vertexData.pData = reinterpret_cast (cubeVertices);
vertexData.RowPitch = vertexBufferSize;
vertexData.SlicePitch = vertexData.RowPitch;

UpdateSubresources(m_commandList.Get(), m_vertexBuffer.Get(), vertexBufferUpload.Get(), 0, 0, 1, &vertexData);

CD3DX12_RESOURCE_BARRIER vertexBufferResourceBarrier =
CD3DX12_RESOURCE_BARRIER::Transition(m_vertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
m_commandList->ResourceBarrier(1, &vertexBufferResourceBarrier);
}
...

We're mainly going to copy that big long mess of gobbledygook and make only the minor changes necessary to make it work to upload our instance buffer. So right underneath the part where the ResourceBarrier was created for the VertexBuffer upload we will put something like this
(Don't ask me about ResourceBarriers, I'm a beginner... It's something to keep the threading straight but I don't know much more.) :

const UINT instanceBufferSize = sizeof(instanceVertices);

// Create the instance buffer resource in the GPU's default heap and copy vertex data into it using the upload heap.
// The upload resource must not be released until after the GPU has finished using it.
Microsoft::WRL::ComPtr
instanceBufferUpload;

// Don't Need - This was defined earlier: CD3DX12_HEAP_PROPERTIES defaultHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
CD3DX12_RESOURCE_DESC instanceBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(instanceBufferSize);
DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
&defaultHeapProperties,
D3D12_HEAP_FLAG_NONE,
&instanceBufferDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(&m_instanceBuffer)));

// Don't Need - This was defined earlier: CD3DX12_HEAP_PROPERTIES uploadHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
&uploadHeapProperties,
D3D12_HEAP_FLAG_NONE,
&instanceBufferDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&instanceBufferUpload)));

NAME_D3D12_OBJECT(m_instanceBuffer);

// Upload the vertex buffer to the GPU.
{
D3D12_SUBRESOURCE_DATA instanceData = {};
instanceData.pData = reinterpret_cast (instanceVertices);
instanceData.RowPitch = instanceBufferSize;
instanceData.SlicePitch = instanceData.RowPitch;

UpdateSubresources(m_commandList.Get(), m_instanceBuffer.Get(), instanceBufferUpload.Get(), 0, 0, 1, &instanceData);

CD3DX12_RESOURCE_BARRIER instanceBufferResourceBarrier =
CD3DX12_RESOURCE_BARRIER::Transition(m_instanceBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
m_commandList->ResourceBarrier(1, &instanceBufferResourceBarrier);
}

Now, we need to create an InstanceBufferView. I don't know why because I don't really understand what I'm doing here, but the code doesn't seem to work without one. At the end of the CreateDeviceDependentResources function there the vertex and index buffer views are created. We will put the code in to create the InstanceBufferView there:

...
// Create vertex/index buffer views.
m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();
m_vertexBufferView.StrideInBytes = sizeof(VertexPositionColor);
m_vertexBufferView.SizeInBytes = sizeof(cubeVertices);

m_instanceBufferView.BufferLocation = m_instanceBuffer->GetGPUVirtualAddress();
m_instanceBufferView.StrideInBytes = sizeof(VertexPositionColor);
m_instanceBufferView.SizeInBytes = sizeof(instanceVertices);

m_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress();
m_indexBufferView.SizeInBytes = sizeof(cubeIndices);
m_indexBufferView.Format = DXGI_FORMAT_R16_UINT;
...

Notice above that when specifying the StrideInBytes size, we were about to use sizeof(VertexPositionColor). This is because we decided to keep using the VertexPositionColor structure that the Vertex Buffer was using and simply ignore the color data. We could have created our *own* data structure that *just* kept the VertexData, but that might have been even more hassle.

Now, all of that mess and we are ready to actually use this data. We have to use it in the Vertex Shader which will be running inside the GPU. You need to open the SampleVertexShader.hlsl file under Content that Microsoft created for you. Two changes will need to be made here. One to the VertexShaderInput and and the other to the "main" function. The VertexShaderInput must match the D3D12_INPUT_ELEMENT_DESC inputLayout[] array we defined earlier so we need to add a few things.

...
// Per-vertex data used as input to the vertex shader.
struct VertexShaderInput
{
float4 pos : SV_POSITION;
float3 color : COLOR0;

float4 instancePos : INSTANCEPOS;
float3 instanceColor : INSTANCECOLOR;

};
...

In the highlighted portion above, the indentifiers to to the right of the colon "INSTANCEPOS" and "INSTANCECOLOR" need to correspond to the identifiers we used when we created the D3D12_INPUT_ELEMENT_DESC inputLayout[] array.

Next we need to update the main as mentioned in a manner similar to what the Rastertex example does in the TextureVertexShader function of [1]. Basically, we take the Instance Data that is passed in via the input parameter and add it to the output. The following highlighted code shows this:

...
// Simple shader to do vertex processing on the GPU.
PixelShaderInput main(VertexShaderInput input)
{
PixelShaderInput output;
float4 pos = float4(input.pos, 1.0f);

pos.x += input.instancePos.x;
pos.y += input.instancePos.y;
pos.z += input.instancePos.z;

// Transform the vertex position into projected space.
pos = mul(pos, model);
pos = mul(pos, view);
pos = mul(pos, projection);
output.pos = pos;

// Pass the color through without modification.
output.color = input.color;

return output;
}
...

Now we need to make a few changes to the Render function. Look for a bracketed section just below
PIXBeginEvent(m_commandList.Get(), 0, L"Draw the cube"); in your Render function of Sample3DSceneRenderer.cpp

...
PIXBeginEvent(m_commandList.Get(), 0, L"Draw the cube");
{
// Set the graphics root signature and descriptor heaps to be used by this frame.
m_commandList->SetGraphicsRootSignature(m_rootSignature.Get());
ID3D12DescriptorHeap* ppHeaps[] = { m_cbvHeap.Get() };
m_commandList->SetDescriptorHeaps(_countof(ppHeaps), ppHeaps);

...

m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_commandList->IASetVertexBuffers(0, 1, &m_vertexBufferView);

m_commandList->IASetVertexBuffers(1, 1, &m_instanceBufferView);

m_commandList->IASetIndexBuffer(&m_indexBufferView);

// Commented - m_commandList->DrawIndexedInstanced(36, 1, 0, 0, 0);
m_commandList->DrawIndexedInstanced(36, 6, 0, 0, 0);

// Indicate that the render target will now be used to present when the command list is done executing.
CD3DX12_RESOURCE_BARRIER presentResourceBarrier =
CD3DX12_RESOURCE_BARRIER::Transition(m_deviceResources->GetRenderTarget(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &presentResourceBarrier);
}
PIXEndEvent(m_commandList.Get());
...

In the above section of the Render function, you will need to call IASetVertexBuffer on your &m_instanceBufferView. The code is highlighted, but notice how the first parameter is 1 instead of 0 like it is when &m_vertexBufferView is set. That is because the instance buffer is in slot 1 while the vertex buffer is in slot 0. Also, look at the section where DrawIndexedInstanced is called. The second parameter has been changed from 1 to 6. That is because instead of drawing one single instance we are now drawing six instances per call. This only works because we are passing six different VertexShaderInput values via the Instance Buffer. Without the instance buffer we wouldn't have an easy by to determine where to draw each of the six instances.

There are other ways to figure out where to get the instancing data from, but I will not get too deeply into them. For example on Page 561 of Luna's [3] (and possibly other references), you will see that SV_InstanceID is a special vertex shader "command" that will allow you to retrieve the instance number that is being worked on from within the Vertex Shader. You can then use the instance number to either calculate the positions of the instnaces or lookup into "global" data. I think Luna is actually using the instanceID to look into a global instance data structure called gInstanceData but it isn't clear to me how the GPU gets visibility to that. It's also not clear to me how Luna's examples in his book tie into the Universal Windows Platform (UWP) that this particular example is based off of. For that reason, I chose to not use take Luna's approach and only use his text as a reference when I'm seriously stuck and Bing can't help me anymore [which is quite often by the way].

That should be about it for all of the setup (assuming I wrote this blog correctly). You should be able to run the program and see at least one cube rotating on the screen, but you will likely be a bit dissapointed because your camera will be too close. One last change that I forgot to tell you about is that we need to back the camera up. In your CreateWindowSizeDependentResources function of your Sample3DSceneRenderer.cpp file, look for code that looks like this:

...
// Eye is at (0,0.7,1.5), looking at point (0,-0.1,0) with the up-vector along the y-axis.

// commented - static const XMVECTORF32 eye = { 0.0f, 0.7f, 1.5f, 0.0f };
static const XMVECTORF32 eye = { 0.0f, 0.7f, 8.0f, 0.0f };

static const XMVECTORF32 at = { 0.0f, -0.1f, 0.0f, 0.0f };
static const XMVECTORF32 up = { 0.0f, 1.0f, 0.0f, 0.0f };
...

In the above code, change the z coordinate of your eye from 1.5f to 8.0f, and then run the program. If I told you everything correctly and you were able to follow me, you should see six cubes in a cross or t pattern rotating around just like the basic cube does in the Microsoft Supplied demo. The cool part is that you can probably figure out now how to modify your code to put the cubes wherever you want on the screen or to even add more 😀. Also, since you are using instancing, you can supposely render thousands of these such cubes on the screen with a single draw call without sacrificing any performance. If you look at the cited references, you will also learn that you can even apply textures and/or colors to these instances to make them unique, but I don't know how to do that right now and you will have to figure that one out for yourself. The end result will generally look something like the below animated GIF.
(The actual DirectX12 rendering will have a much smother gradient with less jerky movement. The below GIF was significantly reduced in quality to conserve bandwidth and conform to GIF standards. Also, as mentioned above, you should now have the skills to modify the rendering code to display additional cubes as you see fit)

Bibliography

1. http://rastertek.com/dx11tut37.html

2. https://www.braynzarsoft.net/viewtutorial/q16390-33-instancing-with-indexed-primitives

3. Luna, Frank D.
Introduction to 3D Game Programming with DirectX 12
Dulles: David Pallai - Mercury Learning and Information, 2016.

©2018 - Shawn Eary
This post is copyright (where allowable) by Shawn Eary and is released under the Free Christian Media Licence (FCML). Content from authors other than Shawn Eary maintain the copyright and license rules that were imposed by the original authors.