Heterogeneous cyber-physical control systems based on digital twins are in demand by Industry 4.0. In accordance with the contemporary systems engineering methodology, such systems are designed at the level of digital models. The paper proposes approaches to formalization and subsequent automation of solving direct and inverse problems of their design. To unify descriptions of heterogeneous components, we follow a viewpoint-based approach to architecture design recommended by the international standard ISO/IEC/IEEE 42010. Following recent trends, we employ category theory as a mathematical framework for the formal description and solution of design problems. Indeed, category theory is a branch of higher algebra specifically aimed at a unified representation of objects of different nature and relationships between them. The design space of a heterogeneous cyber-physical system is constructed as a subcategory of the multicomma category, the objects of which describe possible system architectures with a fixed structural hierarchy represented from a certain viewpoint as diagrams, and morphisms denote actions associated with the parts selection and replacement during the system design. Direct design problems consist in evaluating the properties of the system as a whole by its architecture and are solved using a universal category-theoretic construction of the colimit of the diagram. The solution of inverse problems that require finding variants of the system architecture, which are (sub-, Pareto-) optimal according to the consumer quality criteria, consists in reconstructing diagrams by their colimit edges. For such reconstruction, optimization algorithms of gradient descent type are reasonable to employ, which navigate along the system design space morphisms calculating the path by means of computer algebra. Typical techniques of assembling cyber-physical systems, such as modular composition and aspect weaving, are described in the language of category theory and illustrated. As an example, we outline the design of energy-efficient robotic production lines represented from the behavior viewpoint as discrete-event simulation models.