Afonso Portela BIM A+ European Master in BIM · Parametric modelling and digital design · Dec 2024

Minimal legal flat generator

Portuguese law fixes the smallest area each room in a dwelling may have, and the smallest gross area for each typology, from the studio (T0) to the six-bedroom flat (T6). This study asked whether those rules, written down as data, are enough to generate a legal flat plan inside Grasshopper, without external plugins.

The short answer is no, not yet. The plan below is cut live in your browser with the same algorithm the study arrived at; the schedule beside it checks every space against the law and shows where random cutting breaks. Part two turns the law into the generator itself, with doors, and a solver that cannot produce an illegal plan.

TypologyT2
Gross / net72 / 62.4 m²
Footprint9.3 × 7.7 m
Seed0
Typology
1 : 1.30
Cutting rule

…

Running 500 plans…

#Spacem²MinRGEU

How to read it. The gross area comes from RGEU art. 67 and is offset 35 cm inwards for the external walls (the dark band). A list of directions and split points is consumed one cut at a time, first in, first out, as the Python split_several loop does. Naming the pieces (largest piece to largest requirement) and checking them against art. 66, 68, 69 and 70 is done by this page only: the Grasshopper definition never connected names to geometry. Hatched spaces fail at least one rule.

Context

Why start from the minimum

In 2023 almost 13% of people in Portugal lived in an overcrowded home, against about 9% a year earlier; in the Azores and Madeira the rate passed 20%. Overcrowding is a symptom of many things, but one of them is simply that there are not enough dwellings, and that each new one costs too much to build.

20222023
Overcrowding rate, % of residents, NUTS I. Source: INE, Survey on Income and Living Conditions 2022-2023.

The study had, therefore, two objectives. The internal one was to build a random generator of minimal legal flats in Grasshopper with no external plugins, as a way to learn how to attach textual data (names, rules, adjacencies) to 2D shapes and to manipulate the shapes through those tags, a little like IFC binds properties to geometry. The external one was to contribute, however modestly, to the housing shortage: a tool of this kind, coupled with prefabrication, could help municipal architects produce affordable housing faster.

The aim is the legal minimum, so that the number of dwellings per plot and per euro goes up. Whether a minimal flat is a good place to live, or a cultural shock for those who move into one, is a real question, but not one this system tries to answer.

Input

The law, written as data

The RGEU (Regulamento Geral das Edificações Urbanas, in the 1975 wording of its housing articles) defines a dwelling almost entirely by numbers. These were typed into Grasshopper panels, one list per article, so that every room generated would be born inside its legal limits.

TypologyGross area
art. 67
Bedrooms
art. 66
Living
art. 66
Kitchen
art. 66
Extra area
art. 66
Sanitary
art. 68
Spaces in
the program

Areas in m². The extra area is a mandatory surplus the designer may place anywhere. Above T6 the gross area becomes 1.6 times the habitable area.

Shape, not only area

Area alone would allow a 10.5 m² bedroom 1 m wide. Article 69 prevents it with a rule that changes with size, and article 70 sets the width of corridors:

  1. Below 9.5 m², the smaller side of a room is at least 2.10 m.
  2. From 9.5 to 12 m², the room must contain a circle 2.40 m across.
  3. From 12 to 15 m², the circle grows to 2.70 m.
  4. From 15 m² up, the length may not exceed twice the width.
  5. Corridors are at least 1.10 m wide.

Clear ceiling heights complete the set: 2.40 m in habitable rooms and 2.20 m in halls and bathrooms (art. 65). The proportion limit of article 69 (length at most twice the width) became the first design rule of the generator.

1Attempt

Make every room, then pack them together

The first idea was the intuitive one: generate each room at its legal area, with random proportions inside the 2:1 limit, and then pack the rooms as tightly as possible. A small Python component draws one rectangle per required area, with a width between √A and 1.5√A.

create_rectangle · GhPython 27 lines
Grasshopper canvas generating rectangles of about 10.5 square metres
An earlier version drew the area from a range, so the bedrooms land around 10.5 m² rather than exactly on it.

Packing was entrusted to Galapagos, Grasshopper's evolutionary solver. Rooms received random positions (0 to 30 m) and rotations (0° or 90°); the fitness was the difference between the area of the bounding box around all rooms and the sum of their areas, which is zero when the rooms fill their box exactly.

Galapagos solver window over a Grasshopper definition, with overlapping rectangles
The nesting definition with the Galapagos editor open.

The rooms overlapped, which makes the fitness trivially good. A collision test was added (true or false for each pair, turned into 1 or 0) and multiplied by the fitness. However, multiplying by zero gives zero: as soon as the rooms stopped colliding the fitness was already perfect, whatever the gaps between them, and Galapagos was content to stop shuffling. Adding the collision term with different weights, instead of multiplying, did not change the outcome. No fitness definition that combined both goals was found, and the exploration was abandoned at this point.

2Attempt

Cut the whole flat instead

The problem was then turned around. Instead of assembling rooms into a flat, the flat is taken whole and divided, the way a sheet of plywood is cut on a panel saw. In the vocabulary of operations research (Wäscher, Haußner and Schumann, 2007) this moves from a packing problem to a cutting problem with guillotine cuts, where every cut crosses the piece from side to side. The definition was drawn first in Grasshopper components and then rewritten in Python, which is where the recursion became possible.

  1. Take the bounding box of the net flat area (the gross area of art. 67, offset 35 cm inwards). Working on the bounding box means the flat can be rotated and the same logic still applies, because every split line crosses the rectangle in its full extent.

    Deconstruct the box into its two domains, x and y, and their lengths.

    Hand sketch of a bounding box with its x and y domains and lengths
  2. A 0/1 slider picks the direction d of the cut: it selects the unit vector (x or y) and, at the same time, the length along that direction. A second slider, from 0 to 1, is the split point s.

    Multiplying vector, length and s places a point along the chosen side, anywhere from 0% to 100% of it.

    Hand sketch of the split parameter along a vertical and a horizontal direction
  3. The other direction is found with the index |d − 1|, which always returns the one not chosen. Moving the point by the full length in that direction gives the second end of the split line.

    Intersect the line with the outline, split the outline at those parameters, close each piece with a line from its start to its end point, and join. Lines have to be converted to curves first, or the join refuses them.

    Hand sketch of the outline being split and closed into two pieces
  4. Recursion: keep all pieces in a list. Take the first one out with pop(0), split it, append both halves to the end, and repeat while there are directions and split points left.

    Because the oldest piece is always cut first, the flat is divided in rounds, large pieces before small ones.

    Hand sketch of recursive splits using the pop method
split_curve and split_several · RhinoCommon Python 62 lines
Grasshopper definition feeding random direction and split lists into the Python component
Random lists of directions and split points feeding the recursive component, applied to a list of flats.

The report considers this the main result of the study: the Grasshopper logic, component by component, became a short Python function that can be read, debugged and reused. The plan at the top of this page runs a JavaScript port of the same two functions.

Program

The flat as a list and a graph

Cutting produces pieces, but a flat is a set of named spaces that must connect in a certain way. The program was written as one master list, from which each typology takes its first n items: a T0 has a hall, a living room, a kitchen and a bathroom; each step up adds a private hall, bedrooms, and from T3 a second bathroom.

master_list · Python 29 lines

The connections were written as an adjacency map, one entry per space with the spaces it should open onto: a small graph, in text, of where the doors go.

Typology
The adjacency map drawn as a graph. Spaces outside the selected typology are dashed. The map has no edge between the two halls (red), so the private part of the flat is not yet reachable from the entrance.
Hand sketch of adjacency graphs for T1 and T2 and handwritten grammar rules in Portuguese
The first graphs and grammar rules, in Portuguese: bedrooms side by side or face to face; bedroom to door to corridor or hall, with the bathroom off it; with more than two bedrooms, an en-suite bathroom; entrance to hall, then kitchen, dining, living and, from T2, a guest bathroom. Bedrooms far from the entrance, day spaces near it.
adjacency_map · Python 20 lines

These sketches follow the work of Sara Eloy and José Pinto Duarte on transformation grammars for housing, where a body of existing flats (the Lisbon "rabo-de-bacalhau" buildings, Siza's Malagueira houses) is described by rules that can then generate new or rehabilitated plans.

3Attempt

Tie the number of cuts to the typology

The cutting definition applied the same number of cuts to every flat. The plan was to read the area of the starting rectangle and derive the typology, and from it the number of cuts: in a T0 the first division separates the open living, kitchen and sleeping space and needs no wall, the second one encloses the bathroom; a T1 makes the same cuts but walls the first one; a T2 adds one more; a T3 adds two (a bedroom and a bathroom), and so on.

An elif chain is the natural form for this, since each branch excludes the ones below it even when they are also true. The areas were read correctly, but with placeholder values for direction and split point the component returned an empty data tree, and more time would have been needed to find out why.

split_recursively_by_area · excerpt 20 of 70 lines

The generator on this page does what this attempt was meant to do, by taking the number of cuts from the program (one fewer than the number of spaces) instead of from the area.

4Attempt

Force proportion with an evolutionary solver

Random cuts produce long, narrow spaces that no one would call a room. Galapagos was brought back to minimise two things for each division: the difference between the x and y dimensions of the pieces (within bounds) and the difference between the smaller and the larger area, pushing towards square pieces and cuts near half.

Galapagos editor with an empty fitness graph next to a column of red outlined flats
In a 1 min 30 s run, Galapagos did not show anything resembling a Pareto front.

The logic is sound in principle, but the geometry stayed wrong, with the same long spaces as before. A likely cause is the randomiser of initial conditions, where several consecutive cuts in the same direction produce strips; a fixed sequence of horizontal and vertical cuts would probably help. There is also a deeper conflict: once the starting point is the whole flat, hitting the exact areas of the law becomes a matter of chance.

Outcome

Where the study stopped

Seven extruded flat volumes from T6 down to T0, each divided by internal walls
The final output in Rhino: one flat per typology, cut and extruded.

The result is not a working generator, and the reasons can be listed:

  1. Long, narrow spaces could not be avoided, despite the bounds meant to prevent them.
  2. The number of cuts is the same for every flat; separating it by typology returned an empty data tree.
  3. There is no connection between the textual data (names, adjacencies) and the geometry, and no strategy for it was devised, because the problem itself could not yet be defined.
  4. Without that connection, no doors were placed and the adjacency graph was never enforced.

What remains open

  1. Give every split line a memory of the two pieces it separates, so that it can look up the adjacency list (as CSV or JSON) and decide whether to receive a door, at a random position along its length.
  2. Replace the random directions with a sequence of horizontal and vertical cuts, and test it against the rules of article 69.
  3. Extrude the walls (2.40 m everywhere, the legal minimum for habitable rooms).
  4. Pack the flats into a building outline, mixing typologies for young and old residents in the same building.
  5. Study the axonometry of buildings assembled from these units, and whether denser blocks leave more of each plot for gardens and parking.

The Milestone 1 report predicted that the weak point would be keeping the graph of spatial relations coherent while the geometry is being packed. That proved right, only earlier than expected: the graph never reached the geometry at all. The study set out to understand, from the inside, tools such as Planfinder and the Magnetizing Floor Plan Generator, and it leaves a clearer picture of where their difficulty lives: less in drawing rectangles than in keeping a set of very simple rules true at the same time. It is a restrictive problem, but one whose rules are still open enough to leave a generative algorithm some agency, and a starting point rather than a conclusion.

Overview of the complete Grasshopper definition with labelled groups
The full Grasshopper definition, Milestone 3.
IIPart two · Dec 2026

Generating inside the law

The study generated first and checked afterwards, and random cuts produced a legal plan in fewer than 1% of the attempts. Part two inverts the order. The rules stop being a filter at the end and become the set of moves the generator is allowed to make: a width that would break the law is never on the table, so there is nothing to reject.

Three questions shaped it: how to place the doors, how to make sure every WC can be reached from the common space, and whether the law is better written in Gherkin and Python. A fourth came first: do we have all the rules?

Do we have all the rules?

Not quite, and some of the ones the study used have changed. In December 2026 the RGEU is still in force, but Decree-Law 10/2024 rewrote articles 66 and 68 and revoked article 70, and its full revocation now waits for the technical norms that are to replace it (DL 108/2026). Accessibility (DL 163/2006, section 3.3) applies to every new dwelling and adds its own plan rules. The table lists what constrains a flat's plan and what the solver does with each.

RuleWhat it asksIn the solver

Sources: RGEU consolidated text (PGDL), DL 10/2024, DL 108/2026, DL 163/2006 annex as amended. The numeric tables of art. 66 and 67 were taken from the study's sources and not re-checked against the official images.

How the solver works

  1. The flat is divided into bands parallel to the two facades: rooms on the front, a hall that runs the full width, rooms on the back. Smaller flats may drop the full-width hall and keep it as a cell among the rooms. A T0 is a studio: one room for living and cooking that runs from facade to facade, and a narrow strip with an entrance niche and the WC. It is still a guillotine cutting of the rectangle, as in the study, only the cuts are chosen instead of drawn at random.
  2. For every space and every possible band depth, on a 5 cm grid, the solver lists the widths that pass art. 66, 68, 69, the accessibility rules and art. 71 (the room's facade wall has to take a window of a tenth of its floor). A 9 m² bedroom in a band 2.50 m deep, for instance, may be 3.60 to 4.75 m wide (clear), and never wider: at 12 m² art. 69 would ask for a 2.70 m circle that a 2.50 m band cannot hold. Making a room bigger can make it illegal, which is why the sets are computed rather than assumed.
  3. Spaces are assigned to bands by a depth-first search. A band is possible when its net width belongs to the sum of its spaces' width sets (a Minkowski sum of intervals), which is quick to test, so the search either finds a plan or proves that none exists in this grammar.
  4. Widths are then drawn at random inside their sets, so every plan is different and every plan is legal.
  5. Doors come last, from a door graph. Each space gets one door onto an allowed neighbour, with the 0.80 m leaf and 0.10 m of wall on each side inside the shared partition. A plan whose geometry cannot carry the door graph is redrawn.

The WC rule is a rule of that graph. Among the sanitary spaces, at least one must have its door on the hall; with a single WC, that one. A second WC may open onto a bedroom as an en-suite, the accepted exception to art. 86, which says WCs should not as a rule open onto habitable rooms and never onto the kitchen. Because every room in the band grammar touches the hall along its whole width, a WC can always reach it; the solver still checks the edge, since in the compact layouts that is not guaranteed.

In T0 and T1 the kitchen is a kitchenette inside the living room (art. 66.6), and the merged room must be at least the sum of both table areas (art. 66.7), here with the supplement on top. That is also why a T0 keeps a small entrance niche instead of no hall at all: without it, the WC would open onto the room that holds the kitchenette, and art. 86 says a WC never opens onto the kitchen. The niche is as small as the rules allow, 1.10 m wide, or 1.50 m when the accessibility rules apply.

Light follows art. 71: every habitable room needs glazing of at least a tenth of its floor, and at least 1.08 m², in an exterior wall. This is a constraint on the widths, not a check at the end, so a room too narrow for its window is never drawn. On the street facade every habitable room is glazed across its whole wall; on the other facade windows are sized to the law. Art. 72 asks for cross ventilation of the dwelling through two opposite facades, read here as windows of any room, so a WC window on the back facade counts.

Measuring the plan: space syntax

A legal plan can still be a bad one: a bedroom by the front door, a living room at the end of the corridor. The study's first sketches already had the rule (bedrooms far from the entrance, day spaces near it), but nothing measured it. Space syntax does, by reading the plan as a graph of rooms joined by doors (Hillier and Hanson, 1984; applied to BIM models by Aghabayli, 2021). Three measures are computed for every plan:

  1. Depth: how many doors separate each space from the hall the entrance opens into, drawn as a justified graph with the hall at the bottom.
  2. Walking distance: the shortest route from the entrance door to each room's door, door to door through the rooms, drawn on the plan as red dashed lines.
  3. Mean depth: the average number of doors from a space to all the others; the higher it is, the more private the space.

In the band grammar almost every room is one door from the hall, so depth alone hardly tells them apart; walking distance does. Left to chance, the living room came before every bedroom in only 24% of the plans, and bedrooms ended up on average 0.30 m nearer the entrance than the day spaces. The solver now draws twelve legal variants of each layout and keeps the one with the best privacy gradient. In the 247 sample plans with bedrooms, the living room now comes first in 66% of them, and bedrooms lie on average 2.7 m further from the entrance than the day spaces. The remaining third are mostly compact T1 and T2 plans and corridor plans whose band assignment puts the living room at the far end; making the gradient a rule, rather than a preference, is the next step, and would raise some of the minimum areas in the table above.

TypologyT2
Gross / art. 6772 / 72 m²
Footprint·
Layout·
Typology
1.30 : 1

…

Spacem²Rules
    Space syntax · justified graph from the entrance

    How to read it. Doors swing into the room they serve; the gap in the dark exterior wall on the hall is the entrance. Windows are the light bars in the facade walls: full width on the street (top), sized to art. 71 elsewhere. The gross area starts at the smallest value for which the solver found a plan at this proportion, never below art. 67. Every check in the schedule is recomputed on the finished plan.

    Findings

    Is the art. 67 area enough?

    Running the solver for every typology and footprint gives a question the study could not ask: is the minimum gross area of art. 67 actually enough for a flat that meets every other rule? Under the RGEU alone, from T1 to T6 it is, across most proportions. For T0 it is not: with 35 cm walls all round, the smallest studio found needs 36 m² gross, and up to 39.5 m² depending on the proportion. With a separate kitchen it needed 37.5 to 62 m²; the kitchenette and the studio layout save up to 26 m² on a stretched footprint. Accessibility (turning circles at the entrance and in a 2.00 × 2.20 m bathroom) pushes T0 to 39 to 43 m², T1 to at least 55.5 m², and, depending on the proportion, T2 and the larger flats over art. 67 too.

    Smallest gross area (m², 0.5 m² steps) at which a legal plan was found, by facade : depth proportion. Red cells exceed art. 67; a dot means no plan within 30 m² above it, which in this grammar happens when the facade is too short for every habitable room to have a window. Assumptions: 35 cm exterior and party walls, 10 cm partitions, facades on two opposite sides only.

    Should the law be written in Gherkin and Python?

    Yes, in layers, because the two do different jobs. Gherkin is a language for describing behaviour in sentences that a non-programmer can read and a machine can run; buildingSMART already uses it for the normative rules of its IFC validation service. It is a good form for the law as a contract: each article becomes a feature, quoted in Portuguese, with scenarios that must hold for every plan. It cannot generate anything, though; it only audits.

    So the rules live once, as data (the numbers, each with its article or marked as an assumption), and are read by two independent programs: the JavaScript solver that builds plans inside them, and a Python module that re-implements every check on the finished plan. The Gherkin features call the Python checks. Because the two programs share the numbers but not the code, a bug in either one shows up as a failing scenario.

    features/06_doors.feature · Gherkin excerpt
    rgeu/checks.py · the WC rule in Python excerpt

    Run against 295 solver plans (all typologies, six proportions, half of them with accessibility), the 65 scenarios and 210 steps all pass, including a check that Python, computing the space syntax measures on its own, gets the same depths and walking distances as the solver. Two scenarios break good plans on purpose, a squeezed bedroom and a WC opening onto the kitchen, to prove the checks are not passing everything.

    What remains open

    1. Art. 72 is read literally (windows of the dwelling on both facades); a stricter reading, with habitable rooms on both, would cost the studio its single-room layout.
    2. Facades lie on two opposite sides only, so corner flats, patios and deep plans with light wells are outside the grammar. The hall that runs the full width is legal but generous (around 18 m² in a T4); a hall that stops where the last door is would give that area back to the rooms.
    3. Bathroom fixtures are not drawn; the accessible bathroom is an envelope of 2.00 × 2.20 m, an assumption read from DL 163/2006, not a fixture layout.
    4. Party walls are treated as 35 cm, like facades; thinner party walls would lower every value in the table.
    5. Packing the flats into a building, the study's original ambition, and exporting them to IFC with the rules as properties.

    The study ended by locating the difficulty in keeping a graph of relations true while the geometry changes. Part two keeps it true by never letting the geometry leave the space the graph and the law allow, which turns the rules from a verdict at the end into the material the plan is made of.

    Sources

    References

    1. Aghabayli, A. (2021). Machine Learning Applied to Building Information Models. MSc dissertation, University of Minho. RepositóriUM.
    2. de Almeida, A., Taborda, B., Santos, F., Kwiecinski, K. and Eloy, S. (2016). A genetic algorithm application for automatic layout design of modular residential homes. 2016 IEEE International Conference on Systems, Man, and Cybernetics (SMC), Budapest, 2774-2778. doi:10.1109/SMC.2016.7844659
    3. Hillier, B. and Hanson, J. (1984). The Social Logic of Space. Cambridge University Press.
    4. Hu, R., Huang, Z., Tang, Y., van Kaick, O., Zhang, H. and Huang, H. (2020). Graph2Plan: Learning Floorplan Generation from Layout Graphs. ACM Transactions on Graphics, 39(4).
    5. Nauata, N., Hosseini, S., Chang, K.-H., Chu, H., Cheng, C.-Y. and Furukawa, Y. (2021). House-GAN++: Generative Adversarial Layout Refinement Network towards Intelligent Computational Agent for Professional Architects. CVPR 2021.
    6. Duarte, J. P. (2001). Customizing Mass Housing: A Discursive Grammar for Siza's Malagueira Houses. PhD thesis, MIT.
    7. Eloy, S. and Duarte, J. P. (2014). A Transformation Grammar-Based Methodology for Housing Rehabilitation. In Gero, J. (ed.), Design Computing and Cognition '12. Springer, Dordrecht. doi:10.1007/978-94-017-9112-0_17
    8. Li, Z., Li, S., Hinchcliffe, G., Maitless, N. and Birbilis, N. (2024). Automated architectural space layout planning using a physics-inspired generative design framework. arXiv:2406.14840
    9. Nisztuk, M. and Myszkowski, P. B. (2019). Hybrid Evolutionary Algorithm applied to Automated Floor Plan Generation. International Journal of Architectural Computing, 17(3), 260-283. doi:10.1177/1478077119832982
    10. Strobbe, T., Eloy, S., Pauwels, P., Verstraeten, R., De Meyer, R. and Van Campenhout, J. (2016). A graph-theoretic implementation of the Rabo-de-Bacalhau transformation grammar. AI EDAM, 30(2), 138-158. doi:10.1017/S0890060416000032
    11. Wäscher, G., Haußner, H. and Schumann, H. (2007). An improved typology of cutting and packing problems. European Journal of Operational Research, 183(3), 1109-1130.
    12. Regulamento Geral das Edificações Urbanas (RGEU), Decree-Law 38 382/51, articles 65 to 87; arts. 66 and 68 as amended and art. 70 revoked by Decree-Law 10/2024. Consolidated text: PGDL.
    13. Decree-Law 10/2024 (Simplex urbanístico), art. 24 and 25, and Decree-Law 108/2026, art. 8, on the revocation of the RGEU.
    14. Decree-Law 163/2006, technical norms of accessibility, annex section 3.3 (dwellings), as amended.

    The code in part one was recovered from the original Grasshopper definitions (Assignment02 Milestone 2 and 3, Rhino 8 Python components) and is reproduced as written. The first interactive plan is a JavaScript port of split_curve and split_several; its labelling and RGEU checks are additions of this page. Part two (the solver, the rules data, the Python checks and the Gherkin features) was written in December 2026.